开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜