I have two tables
Titles
ID Name
1 'Title 1'
2 'Title 2'
3 'Title 3'
Comments
ID TitleID Comment
1 1 开发者_StackOverflow中文版'Title 1 Comment #1'
2 1 'Title 1 Commnet #2'
3 2 'Title 2 comment'
I want a recordset that returns all the titles in Titles
and the number of comments for that title, as such
Name # Comments
Title 1 2
Title 2 1
Title 3 0
I worked out how to return all the titles and each comment, but I am having difficulty returning the data with just the count of comments. (My query is below)
SELECT T.ID, T.Name, C.Comment
FROM Titles T
LEFT OUTER JOIN Comments C ON T.ID = C.TitleID
UNION
SELECT T.TitleID, T.Name, C.Comment
FROM Titles T
RIGHT OUTER JOIN Comments C ON T.ID = C.TitleID
Any help would be greatly appreciated.
update
I forgot that I also wanted to return titles without comments. I updated the examples above.
SELECT t.Name as Title, COUNT(c.ID) as NumberOfComments
FROM Titles t
LEFT JOIN Comments c ON c.TitleID = t.ID
GROUP BY t.Name
Ideally you would want to group by the TitleID but you would have to include that in your selection as well. If you're able to ignore that column (or use it) then I would use that instead of t.Name
(or alongside t.Name).
Can also be done with a subselect.
Select T.Name,
(Select Count(*)From Comments C Where C.TitleID=T.ID)As NumComments
From Titles T
The advantage is that no GROUP BY is needed. This can be important if tables in your real data have a lot more columns than the example above.
SELECT title.name, count(comments.comment) as NumComments
FROM titles,comments
WHERE title.id = comment.titleID
Group By title.name
精彩评论