mySQL 提问:如何从post列表中只选择一条评论?
mySQL Query: How to choose just one comment from post list?
Table post:
编号
Table post_comments
id, post_id, 评论, created_at
请求:
SELECT * from post
left join post_comments on post_comments.post_id = post.id
此请求 return 每个 post 的所有评论。
我如何才能将此查询限制为仅针对 return 最后一条评论?
有很多方法可以解决这个每组排名前 1 的问题。
一种方法是使用相关子查询过滤 returns 当前 post:
的最新评论日期
select p.*, c.*
from post p
inner join post_comments c
on c.post_id = p.id
and c.created_at = (
select max(c1.created_at) from post_comments c1 where c1.post_id = c.post_id
)
我也喜欢反left join
解决方案,它确保没有其他评论针对创建日期较晚的 post:
select p.*, c.*
from post p
inner join post_comments c on c.post_id = p.id
left join post_comments c1 on c1.post_id = p.id and c1.created_at > c.created_at
where c1.id is null
Table post: 编号
Table post_comments id, post_id, 评论, created_at
请求:
SELECT * from post
left join post_comments on post_comments.post_id = post.id
此请求 return 每个 post 的所有评论。 我如何才能将此查询限制为仅针对 return 最后一条评论?
有很多方法可以解决这个每组排名前 1 的问题。
一种方法是使用相关子查询过滤 returns 当前 post:
的最新评论日期select p.*, c.*
from post p
inner join post_comments c
on c.post_id = p.id
and c.created_at = (
select max(c1.created_at) from post_comments c1 where c1.post_id = c.post_id
)
我也喜欢反left join
解决方案,它确保没有其他评论针对创建日期较晚的 post:
select p.*, c.*
from post p
inner join post_comments c on c.post_id = p.id
left join post_comments c1 on c1.post_id = p.id and c1.created_at > c.created_at
where c1.id is null