sql – 在第一个表上限制左连接

前端之家收集整理的这篇文章主要介绍了sql – 在第一个表上限制左连接前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两张桌子:宝石和宝石尾巴,它们都是连在一起的.我试图将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 ;

更新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)
原文链接:https://www.f2er.com/mssql/78956.html

猜你在找的MsSQL相关文章