SQL查询对一个表中的行有限制,而不是结果集 [英] SQL query with limit on rows from one table, not the result set
问题描述
我正在运行一个带有联接的简单查询,类似于
I'm running a simple query with a join, similar to
SELECT t1.a, t2.b FROM t1 LEFT JOIN t2 ON ... LIMIT 5
由于t1
在t2
中有很多行(任何大于2的数字),因此LIMIT语句不会返回t1
的前5行和t2
的对应条目,而是返回5行,通常包括2行t1
的-3行.
As t1
has-many rows in t2
( any number above 2 ) the LIMIT statement does not return the first 5 rows from t1
and corresponding entries from t2
, but 5 rows which usually include 2-3 rows from t1
.
如何编写此查询以从t1
获取前5行以及从t2
获得相应条目?
How can I write this query to get the first 5 rows from t1
and the corresponding entries from t2
?
使用MySQL 5.0.45.
Using MySQL 5.0.45.
推荐答案
SELECT t3.a, t2.b FROM (SELECT * FROM t1 LIMIT 5) t3
LEFT JOIN t2 ON ...
请注意,如果您使用没有'order by'子句的limit,则没有定义您将获得5行.如果这不是您想要的,请考虑添加"order by"子句.
Note that if you use limit without an 'order by' clause, it is not defined which 5 rows you will get. Consider adding an 'order by' clause if this is not what you want.
这篇关于SQL查询对一个表中的行有限制,而不是结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!