我想选择每张只带有评论的照片,并且希望该评论成为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.
它似乎正在工作,但是我想知道是否有更好的方法可以做到这一点?
您需要在每张照片上应用max(评论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