Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql LEFT join for right table max value

Tags:

sql

mysql

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?

like image 281
w3father Avatar asked Oct 24 '22 09:10

w3father


1 Answers

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
like image 79
DRapp Avatar answered Oct 27 '22 10:10

DRapp