10

我有两个表: gems 和 gemdetail 是左连接的。我试图将 LEFT JOIN 限制为 gems 表中的 10 条记录。还加入了 2 个其他表(gemreply 和 users),但它们不会导致问题。以下不起作用:

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 有多个详细记录,我只剩下不到 10 个 gem 记录。我已经阅读了每个“限制”帖子,但没有发现这种情况。

更新 1:好的 - 感谢 jviladrich - 它有效。这是代码:

SELECT gems.gemid, gems.title, r.tot, 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 ;

更新 2:下面 yogeshr 的代码也可以工作——可能是我要使用的代码。感谢你们俩!

4

2 回答 2

10

类似的东西

   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)
于 2012-11-23T09:02:55.460 回答
8

试试这个:

SELECT g.gemid, g.title, r.tot, gemdetail.filename
FROM (SELECT * FROM gems WHERE grade = '7' LIMIT 10) g
LEFT JOIN (SELECT gemid, COUNT(*) AS tot FROM gemreply GROUP BY gemid) r
          ON r.gemid = g.gemid
LEFT JOIN gemdetail ON g.gemid = gemdetail.gemid
LEFT JOIN users ON g.userid = users.userid
ORDER BY g.gemid;

这应该有效。

于 2012-11-23T09:13:26.507 回答