我有Release表(id,manga_id,chapterization_id)和章节表(id,chapter)。
我们假设我有
推出
id | manga_id | chapterization_id
--------------------------------
1 | 44 | 333
2 | 55 | 222
3 | 66 | 777
4 | 44 | 888
5 | 44 | 999
Chapterization
id | chapter
------------
111 | 60
222 | 70
333 | 80
444 | 90
777 | 100
888 | 120
999 | 110
我想获取每个manga_id的最大(最新)章节。 漫画44有3个章节,但我想获取它的最新章节,即120
所以最终结果将是id为[2,3,4]的版本 知道如何在PostgreSQL中编写这样的查询吗?
答案 0 :(得分:2)
尝试 -
select r.manga_id, max(c.chapter)
from release r
join chapterization c
on r.chapterization_id = c.id
group by r.manga_id
根据您的评论,如果您还想要r.id,您可以使用以下任一方法。首先是带内联视图的连接。第二个是子查询。两者都应该有相同的结果,并给你你想要的。
select r.manga_id, r.id, c.chapter
from release r
join chapterization c
on r.chapterization_id = c.id
join (select r.manga_id, max(c.chapter) as max_chapter
from release r
join chapterization c
on r.chapterization_id = c.id
group by r.manga_id) x
on r.manga_id = x.manga_id
and c.chapter = x.max_chapter
或
select r.manga_id, r.id, c.chapter
from release r
join chapterization c
on r.chapterization_id = c.id
where c.chapter = (select max(c2.chapter)
from release r2
join chapterization c2
on r2.chapterization_id = c2.id
where r2.manga_id = r.manga_id)
答案 1 :(得分:0)
您可以使用join
和distinct on
子句执行此操作:
select distinct on (r.manga_id) r.manga_id, c.id, c.chapter
from release r join
chapterization c
on r.chapterization_id = c.id
order by r.manga_id, c.chapter desc;