加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQL:从一个表中获取所有记录,从第二个表中获取记录数?

发布时间:2020-12-12 07:30:30 所属栏目:MsSql教程 来源:网络整理
导读:假设有两个表: 表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.. 表B commentID / messageID / Comment 1 / 2 / This is a comment to the second mes
假设有两个表:

表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..

表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

表之间的关系是messageID字段.

我想要一个生成这样的结果的查询,其中我从表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中.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读