gpt4 book ai didi

sql - 一次查询从三个表中获取数据

转载 作者:行者123 更新时间:2023-12-01 09:34:02 26 4
gpt4 key购买 nike

我正在尝试一次从三个表中检索数据。表格如下所示:

类别

id
category
messageid

消息

id
title
message

评论

id
messageid
message

我想要得到的是 1 条消息(因为我有一个基于 id 3WHERE 子句),3 个类别(因为有 3 个类别链接到消息)和 2 条评论(因为有 2 条评论链接到该消息)。

我正在尝试通过使用以下查询来检索数据:

SELECT categories.category, messages.id, messages.title, messages.message, comments.count, comments.id as commentid, comments.message as commentmessage
FROM categories
RIGHT JOIN
(SELECT id, title, message
FROM messages WHERE messaged.id = 3) messages
ON messages.id = categories.messageid
LEFT JOIN
(SELECT count(id), id, message
FROM comments
GROUP BY id, message) comments
ON messages.id = comments.messageid
ORDER BY article.id DESC

但是,当运行此查询时,我得到 6 个结果:

category      id  title      message      count  commentid  commentmessage
test 3 the title the message 1 6 comment 1
test 3 the title the message 1 5 comment 2
installation 3 the title the message 1 6 comment 1
installation 3 the title the message 1 5 comment 2
question 3 the title the message 1 6 comment 1
question 3 the title the message 1 5 comment 2

我期望的结果类似于:

category      id  title      message      count  commentid  commentmessage
test 3 the title the message 1 6 comment 1
question 3 the title the message 1 5 comment 2
installation 3 the title the message 1 null null

只有三行我应该能够获得所有需要的数据。这甚至可能吗?我做错了吗™?

最佳答案

这里有几个问题,正如评论中提到的那样。

首先,由于您要连接三个表,因此您得到的答案是正确的。 1 x 2 x 3 行 = 6。

其次,您的评论汇总并没有真正汇总任何内容。正如您在结果中看到的那样,计数始终为 1,而我希望您认为两条评论为 2。由于您在 id 上进行分组,因此对每个唯一 id 执行计数,该 id 始终为 1。我想你可能想在 messageid 上分组

SELECT count(*), messageid
FROM comments
GROUP BY messageid

您需要进行另一个联接或单独的查询才能获得评论本身。

正如评论中所讨论的,您通常不会以这种方式获得信息;您通常只需进行三个查询,因为其中两个关系是一对多的。如果您的类别很短(并且您使用的是 SQL Server),您可以将类别压缩到它们自己的列中(即“测试、安装、问题”)。以下是您将如何做到的。

select id, title, message,
(select CAST(category + ', ' as nvarchar(max))
from @Categories c where messageid = m.id
for xml path('')) as Categories
from @Messages m
where m.id = 3

实际上,有几种方法可以做到这一点,但这既快速又肮脏。然后,您只需要一个额外的评论查询。您可以像这样加入上一个查询并在两行中​​获取所有信息

select m.id, title, m.message,
(select CAST(category + ', ' as nvarchar(max))
from @Categories c where messageid = m.id
for xml path('')) as Categories,
cm.message
from @Messages m
left outer join @Comments cm on m.id = cm.messageid
where m.id = 3

但同样,您可能只想进行额外查询以避免重复信息。

最后,我想展示您可能希望如何计算评论数。

select m.id, title, m.message,
(select CAST(category + ', ' as nvarchar(max))
from @Categories c where messageid = m.id
for xml path('')) as Categories,
CommentCount,
cm.message
from @Messages m
left outer join
(
select messageid, COUNT(*) CommentCount
from @Comments
group by messageid
) rsCommentCount on rsCommentCount.messageid = m.id

And lastly, here is a link showing that working.

关于sql - 一次查询从三个表中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11658191/

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