SQL Query获取一行,以及关联行的计数

时间:2009-06-10 20:53:33

标签: sql sql-server

我有两张桌子,如下:

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

6 个答案:

答案 0 :(得分:17)

这通常比子查询方法更快,但一如既往,您必须对系统进行分析以确保:

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 :(得分:1)

select title, NumComments = (select count(*) 
from comments where parentID = id) from Articles

答案 2 :(得分:1)

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

答案 3 :(得分:0)

我会这样做:

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?

答案 4 :(得分:0)

SELECT
Articles.ID
,Articles.TItle
,(SELECT Count(*) FROM Comments WHERE Comments.ParentId = Artices.ID) AS CommentCount
FROM Articles

答案 5 :(得分:0)

SELECT Articles.Title,COUNT(Comments.ID) FROM Articles INNER JOIN关于Articles.ID = Comments.ParentID的评论 GROUP BY Articles.Title