我有两个表: 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 的代码也可以工作——可能是我要使用的代码。感谢你们俩!