假设有两个表:
TABLE A
messageID / Message / More..
1 / This is the first message / Etc..
2 / This is the second message / Etc..
3 / This is the third message / Etc..
TABLE B
commentID / messageID / Comment
1 / 2 / This is a comment to the second message
2 / 2 / This is another comment to the second message
3 / 3 / This is a comment to the third message
表之间的联系是消息ID field.
我想要一个生成这样的结果的查询,其中我从表 A 中提取所有字段,并计算表 B 中每条消息的评论数量,如下所示:
messageID / Message / More... / CommentCount
1 / This is the first message / etc... / 0
2 / This is the second message / etc... / 2
3 / This is the third message / etc... / 1
我尝试过这样的事情:
SELECT tableA.*, count(commentID) as commentcount
FROM tableA LEFT JOIN tableB ON tableA.messageID = tableB.messageID GROUP BY messageID
但它不起作用。有任何想法吗?看起来应该可以在一个查询中完成此操作。我正在使用 MSSQL。谢谢你的帮助。
标量子查询将起作用:
SELECT tableA.*
,(SELECT count(commentID) FROM tableB WHERE tableA.messageID = tableB.messageID) as commentcount
FROM tableA
和往常一样,剥这只猫的皮的方法有很多,性能也各不相同。
当使用GROUP BY
,输出中的所有列都需要位于GROUP BY
或者在聚合函数中 - 即使 messageID 中的其他列没有变化,它们仍然需要位于GROUP BY
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)