mysql LEFT加入右表最大值

时间:2011-06-07 15:44:14

标签: mysql sql

我想选择只有一条评论的每张照片,我希望评论为最大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.

它似乎有效,但我想知道是否有更好的方法来做到这一点?

2 个答案:

答案 0 :(得分:5)

您需要在每张照片上应用最大值(评论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

答案 1 :(得分:-2)

您也可以使用交叉联接:

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