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.
This will normally be faster than the subquery approach, but as always you have to profile your system to be sure:
SELECT Articles.Title, COUNT(Comments.ID) FROM Articles INNER JOIN Comments ON Articles.ID = Comments.ParentID GROUP BY Articles.Title
I'd do it like this:
This might help in deciding between joining or using sub query:
Transact-SQL - sub query or left-join?