gpt4 book ai didi

mysql - 在 mysql 中,如何连接第二个表并获取具有最新日期的行?

转载 作者:行者123 更新时间:2023-11-29 02:43:51 25 4
gpt4 key购买 nike

在 mysql 中我有两个表:QuestionCommentary。这是它们的样子:

问题:ID、标题

评论:QuestionId、内容、创建(日期字段)

QuestionId 是问题 ID 的外键。

所以我在问题和评论之间有一个0 到多的关系。也就是说,一个问题可以有 0..n 条评论。

我想做的是显示所有问题以及最新的评论(Created 字段)(如果有)。因此,如果没有评论,问题仍然必须显示,但在评论的内容字段中为 null。

我相信我几乎可以在这个查询中使用它,只是它只检索评论的问题。如前所述,我也想要那些没有评论的问题。

select 
q.Id AS Id,
q.Title AS Title,
c.Content AS Content
from question AS q
left join commentary as c on c.QuestionId = q.Id
where
c.Created = (
select MAX(created)
from commentary
where questionid = q.Id
)

如何调整脚本?

最佳答案

where 子句仅返回评论行具有最大创建日期的行,这在没有评论记录时不成立。您只需要包含注释 question_ID 为 null 的行,当没有注释时,它应该始终为 true。

select 
q.Id AS Id,
q.Title AS Title,
c.Content AS Content
from question AS q
left join commentary as c on c.QuestionId = q.Id
where
c.Created = (
select MAX(created)
from commentary
where questionid = q.Id
)
or
c.QuestionId is null

关于mysql - 在 mysql 中,如何连接第二个表并获取具有最新日期的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46008993/

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