我希望选择只有一个评论的每张照片,并且希望该评论是具有最大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.
看起来它正在工作,但我想知道是否有更好的方法来做到这一点?
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
你也可以使用交叉连接来实现这个:
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