How to COUNT(*) from multi-table query?
I have two tables, Snippets and Comments. Snippets has an Id column and Comments has a SnippetId column.
I want to count the number of comments for each snippet.
I tried this:
SELECT
S.Id,
S.Title,
COUNT(*) AS CommentCount
FROM
Snippets S,
Comments C
WHERE
S.Id = C.SnippetId
but it does not work. It returns the total number of comments, and only returns one row.
I want to have a result like this:
开发者_C百科Id | Title | CommentCount
1 | Test | 314
2 | Test2 | 42
How can I achieve this?
You almost have it correct; you're just missing a GROUP BY
clause:
SELECT
S.Id,
S.Title,
COUNT(*) AS CommentCount
FROM
Snippets S,
Comments C
WHERE
S.Id = C.SnippetId
GROUP BY S.Id, S.Title
how about add
group by S.Id ,S.Title
at the end of your sql
精彩评论