【问题标题】:SQL Query to get a row, and the count of associated rowsSQL Query 获取一行,以及关联行的计数
【发布时间】:2009-06-10 20:53:33
【问题描述】:

我有两张桌子,像这样:

#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"

我一直想知道,得到以下结果的最优雅的方法是什么:

ID | Title |          NumComments
1    "Article title"      2
2    "2nd article title"  0

这是为 SQL Server 准备的。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    这通常比子查询方法更快,但您必须像往常一样分析您的系统以确保:

    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
    

    【讨论】:

    • 该死的你打败了我... + 1
    • 嗯,先答对就得积分!谢谢乔尔!
    • Count(*) 在应该返回 0 时返回 1。
    • @rixth:实际上,David B 是正确的,并且存在错误。不过现在应该已经修复了。
    【解决方案2】:
    select title, NumComments = (select count(*) 
    from comments where parentID = id) from Articles
    

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

      • 是的,我知道。正在尝试更新并被覆盖。现在修好了。
      【解决方案4】:

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

      【讨论】:

        【解决方案5】:
        SELECT
        Articles.ID
        ,Articles.TItle
        ,(SELECT Count(*) FROM Comments WHERE Comments.ParentId = Artices.ID) AS CommentCount
        FROM Articles
        

        【讨论】:

          【解决方案6】:

          我会这样做:

          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
          

          这可能有助于决定是加入还是使用子查询:

          Transact-SQL - sub query or left-join?

          【讨论】:

          • 这个小问题。 A.ID = C.ID 意味着您只会将一个独特的评论与一篇独特的文章相关联。你的意思是 A.ParentID=C.ID
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-10-22
          • 2021-01-18
          • 1970-01-01
          • 1970-01-01
          • 2015-03-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多