我有两张桌子:宝石和宝石尾巴,它们都是连在一起的.我试图将LEFT JOIN限制为gems表中的10条记录.还有另外两个表(gemreply和用户)加入了,但它们没有对这个问题做出贡献.以下不起作用:
SELECT gems.gemid,gems.title,r.tot,gemdetail.filename FROM ((gems LEFT JOIN (SELECT gemid,COUNT(*) AS tot FROM gemreply GROUP BY gemid) AS r ON gems.gemid = r.gemid) LEFT JOIN gemdetail ON gems.gemid = gemdetail.gemid) LEFT JOIN users ON gems.userid = users.userid WHERE gems.grade = '7' ORDER BY gems.gemid LIMIT 0,10;
这会将返回的行总数限制为10,但由于每个gem有多个详细记录,因此我留下的gem记录少于10个.我已阅读每篇“LIMIT”帖子,但未发现这种情况.
更新1:
好的 – 感谢jviladrich – 它奏效了.这是代码:
SELECT gems.gemid,gemdetail.filename FROM ((gems INNER JOIN (SELECT gems.gemid from gems WHERE gems.grade = '7' ORDER BY gems.gemid LIMIT 0,10) g ON (gems.gemid = g.gemid) LEFT JOIN (SELECT gemid,COUNT(*) AS tot FROM gemreply GROUP BY gemid) AS r ON gems.gemid = r.gemid) LEFT JOIN gemdetail ON gems.gemid = gemdetail.gemid) LEFT JOIN users ON gems.userid = users.userid ;
解决方法
这样的事情
SELECT * FROM A INNER JOIN ( SELECT * FROM A WHERE A.FIELD1='X' ORDER BY A.FIELD2 LIMIT 10) X ON (A.KEYFIELD=X.KEYFIELD) LEFT JOIN B ON (A.FIELD = B.FIELD) LEFT JOIN C ON (A.FIELD = C.FIELD)