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

2020-06-21 07:12发布

问题:

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.

回答1:

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


回答2:

select title, NumComments = (select count(*) 
from comments where parentID = id) from Articles


回答3:

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


回答4:

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



回答5:

SELECT
Articles.ID
,Articles.TItle
,(SELECT Count(*) FROM Comments WHERE Comments.ParentId = Artices.ID) AS CommentCount
FROM Articles


回答6:

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?