Mysql
 SQL >> Database >  >> RDS >> Mysql

MySQL: LEFT JOIN con il valore massimo della tabella di destra

Devi applicare max(comment_id) per ogni foto (assumendo che il comment ID sia auto-incrementante e quindi sempre il più recente):

select p.*, tbc.Comment
from tb_photos p
LEFT JOIN (
  select c.photos_id, max(c.id) as lastCommentPerPhoto
  from tb_comments c
  group by c.photos_id
) LastPhotoComment on p.id = LastPhotoComment.photos_id
LEFT JOIN tb_comments tbc on LastPhotoComment.lastCommentPerPhoto = tbc.id

Alternativa con window function

Su MySQL 8 puoi evitare la doppia JOIN:

select p.*, c.Comment
from tb_photos p
left join (
  select c.*, row_number() over (partition by photos_id order by id desc) rn
  from tb_comments c
) c on c.photos_id = p.id and c.rn = 1