gpt4 book ai didi

sql - 在第一个表上限制左联接

转载 作者:行者123 更新时间:2023-12-04 05:54:27 26 4
gpt4 key购买 nike

我有两个表:gem和gemdetail保持连接状态。我试图将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有多个明细记录,所以我剩下不到10个gem记录。我已经阅读了每个“LIMIT”帖子,但没有发现这种情况。

更新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的代码也可以使用-可能是我将要使用的代码。感谢你们俩!

最佳答案

像这样

   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)

关于sql - 在第一个表上限制左联接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13525656/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com