MYSQL Join - Parent和Child表连接并仅获取子表中的最新记录

Buj*_*jji 2 mysql sql join greatest-n-per-group

我有两张表帖子和评论

邮政表

Post_id
Post_content
Run Code Online (Sandbox Code Playgroud)

评论表

comment_id
Comment
post_id
created_date
Run Code Online (Sandbox Code Playgroud)

一篇文章可以有多个评论或零评论

我的要求是使用左外连接获取帖子的最新评论.

我的意思是结果应该是具有以下列的帖子的一个记录.

post_id,post_content ,comment_id,comment 
Run Code Online (Sandbox Code Playgroud)

简单来说,如果帖子存在,帖子应该与他们的最新评论相处.

(目前系统首先获得帖子,然后再次访问服务器以获取最新的评论显示,想到一次性获取它们,因为我们最初只显示一条评论...不确定什么应该是最好的方法如果想要显示多条评论..?)

谢谢

问候

基兰

Bra*_*vic 7

SELECT Post.post_id, post_content, comment_id, comment
FROM
    Post LEFT JOIN Comments
        ON Post.post_id = Comments.post_id
        AND created_date = (
            SELECT MAX(created_date)
            FROM Comments
            WHERE Post.post_id = Comments.post_id
        )
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你应该考虑建立索引Comments {post_id, created_date}以获得最佳性能,但要留意如果你正使用InnoDB(请参见"集群的缺点",在非主键索引开销的这篇文章).