小编典典

通过一对多关系表仅选择具有最大字段的一行

sql

我有2个表格,Chapter表格中有很多行,其中manga_id是Manga表格的ID

漫画桌

ID | NAME      | SLUG 
1    One Piece   one-piece
2    Naruto      naruto
3    Gintama     gintama

章表

MANGA_ID | NAME    | SLUG             | CREATED_AT
1          Chap 1    One-Piece-Chap-1   2016/01/01
1          Chap 2    One-Piece-Chap-2   2016/01/02
1          Chap 3    One-Piece-Chap-3   2016/01/03
2          Chap 1    Naruto-Chap-1      2016/01/02
2          Chap 2    Naruto-Chap-2      2016/01/03
2          Chap 3    Naruto-Chap-3      2016/01/04
3          Chap 1    Gintama-Chap-1     2016/01/07
3          Chap 4    Gintama-Chap-4     2016/01/09

我只选择1个漫画,按created_atDESC的顺序排列1章

我要查找的示例表:

Manga_ID | Manga_NAME | NAME    | SLUG             | CREATED_AT
3          Gintama      Chap 4    Gintama-Chap-4     2016/01/09
2          Naruto       Chap 3    Naruto-Chap-3      2016/01/04
1          One Piece    Chap 3    One-Piece-Chap-3   2016/01/03

我真的很感谢任何对此主题的回答,并节省我的时间


阅读 179

收藏
2021-04-28

共1个答案

小编典典

SELECT mt.id as MANGA_ID, mt.NAME as MANGA_NAME, ct.NAME, ct.SLUG, MAX(ct.CREATED_AT) as CREATED_AT FROM Chapter ct LEFT JOIN Manga mt ON (mt.id = ct.MANGA_ID) GROUP BY ct.MANGA_ID

这应该可以解决问题。

2021-04-28