gpt4 book ai didi

mysql - 从 MySQL 中的另一个表中获取最新行

转载 作者:行者123 更新时间:2023-12-01 00:16:45 26 4
gpt4 key购买 nike

假设我有两个表,新闻和评论。

news (
id,
subject,
body,
posted
)

comments (
id,
parent, // points to news.id
message,
name,
posted
)

我想创建一个查询,以获取最新的 x # 条新闻以及每条新闻的最新评论的名称和发布日期。

就选择子查询中的所有评论而言,速度问题不是一个选项。

最佳答案

我刚刚意识到如果新闻表没有附加评论,查询不会返回结果,这里是修复以及为帖子总数添加的列:

SELECT news.*, comments.name, comments.posted, (SELECT count(id) FROM comments WHERE comments.parent = news.id) AS numComments
FROM news
LEFT JOIN comments
ON news.id = comments.parent
AND comments.id = (SELECT max(id) FROM comments WHERE parent = news.id)

关于mysql - 从 MySQL 中的另一个表中获取最新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/469338/

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