tags:

views:

170

answers:

6

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  A: 
select title, NumComments = (select count(*) 
from comments where parentID = id) from Articles
tekBlues
+1, you were darn fast on the answer
KM
+14  A: 

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
Joel Coehoorn
+1 ... My thought too; you're too fast, Joel.
Adrien
dang it you beat me to it... + 1
Jason Heine
Well, first in with the correct answer gets the points! Thanks Joel!
Tom R
Count(*) is returning 1 when it should return 0.
David B
@rixth: actually, David B is correct and there was a bug. It should be fixed now, though.
Joel Coehoorn
Fixed now. Yup.
David B
+1  A: 
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
Matthew Jones
I'm afraid you won't get the articles without comments...
tekBlues
Ya I know. Was trying to update and got overwritten. Fixed it now.
Matthew Jones
A: 

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:

http://stackoverflow.com/questions/117952/transact-sql-sub-query-or-left-join

Nick
Small problem with this. A.ID = C.ID means you will only associate one unique comment to one unique article. Did you mean A.ParentID=C.ID
Matthew Jones
@Matthew - D'oh! Good point, corrected :)
Nick
A: 
SELECT
Articles.ID
,Articles.TItle
,(SELECT Count(*) FROM Comments WHERE Comments.ParentId = Artices.ID) AS CommentCount
FROM Articles
James Conigliaro
A: 

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

Justin Balvanz