sql >> Base de Datos >  >> RDS >> Mysql

mysql LEFT join para el valor máximo de la tabla derecha

debe aplicar el máximo (ID de comentario) en cada foto (suponiendo que el ID de comentario se incremente automáticamente y, por lo tanto, siempre sea el más reciente agregado a la tabla)

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