简体   繁体   中英

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_comments 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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