【问题标题】:How to COUNT(*) from multi-table query?如何从多表查询中计数(*)?
【发布时间】:2011-09-25 14:00:59
【问题描述】:

我有两个表格,Snippets 和 Comments。 Snippets 有一个 Id 列,Comments 有一个 SnippetId 列。

我要统计每个sn-p的cmets个数。

我试过了:

   SELECT
      S.Id,
      S.Title,
      COUNT(*) AS CommentCount
    FROM
      Snippets S,
      Comments C
    WHERE
      S.Id = C.SnippetId

但它不起作用。它返回 cmets 的总数,并且只返回一行。

我想要这样的结果:

Id | Title | CommentCount
 1 |  Test |          314
 2 | Test2 |           42

我怎样才能做到这一点?

【问题讨论】:

    标签: sql select count


    【解决方案1】:

    你几乎说对了;你只是缺少一个GROUP BY 子句:

    SELECT
      S.Id,
      S.Title,
      COUNT(*) AS CommentCount
    FROM
      Snippets S,
      Comments C
    WHERE
      S.Id = C.SnippetId
    GROUP BY S.Id, S.Title
    

    【讨论】:

      【解决方案2】:

      添加怎么样

      group by S.Id ,S.Title
      

      在你的 sql 结尾

      【讨论】:

        猜你喜欢
        • 2019-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        相关资源
        最近更新 更多