开发者

mysql LEFT join for right table max value

I want to select every photo with only one comment and I want that comment to be the one with the maximum ID

I have tried following:

SELECT
    p.id,
    p.title,
    MAX(c.id),
    c.comment
FROM tb_photos AS p
    LEFT JOIN tb_com开发者_StackOverflow中文版ments AS c ON p.id=c.photos_id.

It seems to be working, but I am wondering if there is a better way to do this?


you need to apply the max( comment ID ) on each photo (assuming the comment ID is auto-increment and thus always the most recent added to the table)

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


You can also do this with a cross join:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜