mysql LEFT加入右表最大值

w3f*_*her 5 mysql sql

我想选择只有一条评论的每张照片,我希望该评论是具有最大ID的评论

我试过以下:

SELECT
    p.id,
    p.title,
    MAX(c.id),
    c.comment
FROM tb_photos AS p
    LEFT JOIN tb_comments AS c ON p.id=c.photos_id.
Run Code Online (Sandbox Code Playgroud)

它似乎有效,但我想知道是否有更好的方法来做到这一点?

DRa*_*app 5

你需要在每张照片上应用最大值(评论ID)(假设评论ID是自动递增的,因此总是最新添加到表中)

select
      p.*,
      tbc.Comment
   from
      tb_photos p
         LEFT JOIN ( select c.photos_id, 
                            max( c.id ) lastCommentPerPhoto
                        from
                           tb_comments c
                        group by
                           c.photos_id
                        order by
                           c.Photos_id ) LastPhotoComment
            on p.id = LastPhotoComment.photos_id
            LEFT JOIN tb_comments tbc
               on LastPhotoComment.LastCommentPerPhoto = tbc.id
Run Code Online (Sandbox Code Playgroud)