gpt4 book ai didi

SQL 查询获取一行以及关联行的计数

转载 作者:行者123 更新时间:2023-12-03 01:05:02 25 4
gpt4 key购买 nike

我有两个表,如下所示:

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

最佳答案

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

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

关于SQL 查询获取一行以及关联行的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/978093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com