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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With