sql - 左连接 - 计数

时间:2010-02-07 03:15:49

标签: sql sql-server tsql join

假设我有两张桌子。文章和评论。

当我从articles表中选择列时,我还想在同一个select语句中选择文章的注释数量...(假设这两个表之间的公共字段是articleid)

我该怎么做?我可以完成它,但我不知道我的方式是否有效,所以我想学习正确的方法。

5 个答案:

答案 0 :(得分:11)

这应该更有效,因为group by仅在Comment表上完成。

SELECT  
       a.ArticleID, 
       a.Article, 
       isnull(c.Cnt, 0) as Cnt 
FROM Article a 
LEFT JOIN 
    (SELECT c.ArticleID, count(1) Cnt
     FROM Comment c
    GROUP BY c.ArticleID) as c
ON c.ArticleID=a.ArticleID 
ORDER BY 1

答案 1 :(得分:4)

使用:

   SELECT a.articleid, 
          COUNT(*) AS num_comments
     FROM ARTICLES a
LEFT JOIN COMMENTS c ON c.articleid = a.articleid
 GROUP BY a.articleid

无论您希望从ARTICLES表中找到哪些列,您都必须在GROUP BY子句中定义,因为它们没有对它们执行聚合函数。

答案 2 :(得分:2)

应该这样做..

SELECT
   article_column_1, article_column_2, count( ct.articleid) as comments
FROM
   article_table at
   LEFT OUTER JOIN comment_table ct ON at.articleid = ct.articleid
GROUP BY 
   article_column_1, article_column_2

答案 3 :(得分:0)

SELECT 
       a.Article,
       a.ArticleID,
       t.COUNTOFCOMMENTS
FROM
       Article a
LEFT JOIN
       Comment c
ON c.ArticleID=a.ArticleID
LEFT JOIN
(SELECT ArticleID, COUNT(CommentID) AS COUNTOFCOMMENTS FROM Comments GROUP BY ArticleID) t
ON t.ArticleID = a.ArticleID

答案 4 :(得分:0)

    -- Working Syntax example from my environment changed to fit this context. 
SELECT a.article
    ,A.articleid
    ,(
        SELECT Count(B.articleid)
        FROM dbo.comment AS B
        WHERE A.articleid = B.articleid
        ) AS comment#
    ,(
        SELECT Count(C.articleid)
        FROM dbo.comments AS C
        WHERE A.articleid = C.articleid
        ) AS comments#
FROM dbo.article AS A;