从与另一个表连接的数据库表返回计数
我有两个表
Titles
ID Name
1 'Title 1'
2 'Title 2'
3 'Title 3'
Comments
ID TitleID Comment
1 1 'Title 1 Comment #1'
2 1 'Title 1 Commnet #2'
3 2 'Title 2 comment'
我想要一个记录集,它返回 Titles
中的所有标题以及该标题的评论数,因此
Name # Comments
Title 1 2
Title 2 1
Title 3 0
我弄清楚了如何返回所有标题和每条评论,但我仅凭评论数量很难返回数据。 (我的查询如下)
SELECT T.ID, T.Name, C.Comment
FROM Titles T
LEFT OUTER JOIN Comments C ON T.ID = C.TitleID
UNION
SELECT T.TitleID, T.Name, C.Comment
FROM Titles T
RIGHT OUTER JOIN Comments C ON T.ID = C.TitleID
任何帮助将不胜感激。
更新
我忘记了我也想返回不带评论的标题。我更新了上面的例子。
I have two tables
Titles
ID Name
1 'Title 1'
2 'Title 2'
3 'Title 3'
Comments
ID TitleID Comment
1 1 'Title 1 Comment #1'
2 1 'Title 1 Commnet #2'
3 2 'Title 2 comment'
I want a recordset that returns all the titles in Titles
and the number of comments for that title, as such
Name # Comments
Title 1 2
Title 2 1
Title 3 0
I worked out how to return all the titles and each comment, but I am having difficulty returning the data with just the count of comments. (My query is below)
SELECT T.ID, T.Name, C.Comment
FROM Titles T
LEFT OUTER JOIN Comments C ON T.ID = C.TitleID
UNION
SELECT T.TitleID, T.Name, C.Comment
FROM Titles T
RIGHT OUTER JOIN Comments C ON T.ID = C.TitleID
Any help would be greatly appreciated.
update
I forgot that I also wanted to return titles without comments. I updated the examples above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
理想情况下,您希望按 TitleID 进行分组,但您也必须将其包含在您的选择中。如果您能够忽略该列(或使用它),那么我将使用它来代替
t.Name
(或与 t.Name 一起)。Ideally you would want to group by the TitleID but you would have to include that in your selection as well. If you're able to ignore that column (or use it) then I would use that instead of
t.Name
(or alongside t.Name).也可以通过子选择来完成。
优点是不需要GROUP BY。如果实际数据中的表的列数比上面的示例多得多,这一点可能很重要。
Can also be done with a subselect.
The advantage is that no GROUP BY is needed. This can be important if tables in your real data have a lot more columns than the example above.