繁体   English   中英

mysql 左连接右表最大值

[英]mysql LEFT join for right table max value

我想 select 每张只有一条评论的照片,我希望该评论是具有最大 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.

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

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

您也可以使用交叉连接来执行此操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM