SQL Query to get a row, and the count of associate

2020-06-21 07:04发布

I have two tables, like this:

#Articles:
ID | Title
1    "Article title"
2    "2nd article title"

#Comments:
ID | ParentID | Comment
1    1          "This is my comment"
2    1          "This is my other comment"

I've always wanted to know, what is the most elegant way to get the following result:

ID | Title |          NumComments
1    "Article title"      2
2    "2nd article title"  0

This is for SQL Server.

6条回答
冷血范
2楼-- · 2020-06-21 07:26
SELECT
Articles.ID
,Articles.TItle
,(SELECT Count(*) FROM Comments WHERE Comments.ParentId = Artices.ID) AS CommentCount
FROM Articles
查看更多
闹够了就滚
3楼-- · 2020-06-21 07:33
SELECT 
   A.ID, A.Title, COUNT(C.ID) 
FROM 
   Articles AS A 
LEFT JOIN 
   Comments AS C ON C.ParentID = A.ID 
GROUP BY 
   A.ID, A.Title 
ORDER BY 
   A.ID
查看更多
▲ chillily
4楼-- · 2020-06-21 07:42
select title, NumComments = (select count(*) 
from comments where parentID = id) from Articles
查看更多
混吃等死
5楼-- · 2020-06-21 07:43

This will normally be faster than the subquery approach, but as always you have to profile your system to be sure:

SELECT a.ID, a.Title, COUNT(c.ID) AS NumComments
FROM Articles a
LEFT JOIN Comments c ON c.ParentID = a.ID
GROUP BY a.ID, a.Title
查看更多
老娘就宠你
6楼-- · 2020-06-21 07:45

SELECT Articles.Title, COUNT(Comments.ID) FROM Articles INNER JOIN Comments ON Articles.ID = Comments.ParentID GROUP BY Articles.Title

查看更多
放我归山
7楼-- · 2020-06-21 07:47

I'd do it like this:

select a.ID 'ArticleId',
       a.Title,
       count(c.ID) 'NumComments'
from   Articles a
left join
       Comments c
on     a.ID = c.ParentID
group by a.ID, a.Title

This might help in deciding between joining or using sub query:

Transact-SQL - sub query or left-join?

查看更多
登录 后发表回答