[英]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我想 select 每张只有一条评论的照片,我希望该评论是具有最大 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)您需要在每张照片上应用最大(评论 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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.