MySQL左连接右表最大值

5

我希望选择只有一个评论的每张照片,并且希望该评论是具有最大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.

看起来它正在工作,但我想知道是否有更好的方法来做到这一点?

2个回答

5
您需要在每张照片上应用max(评论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

-2

你也可以使用交叉连接来实现这个:

select
      p.*,
      LastPhotoComment.Comment
   from
      tb_photos p
         cross join ( select top 1 c.Comment
                        from
                           tb_comments c
                        where
                           c.photos_id = p.id
                        order by
                           c.id DESC ) LastPhotoComment

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接