如何获取MySQL中每个系列的最后一集?

时间:2017-10-23 11:06:55

标签: mysql sql

我有以下表结构:

id | series_id | season | episode

该表代表电视节目剧集。

我想获取每个series_id的最后一集。

示例:

id | series_id | season | episode
1       1          1         9
2       1          2         1
3       2          1         1
4       2          1         2

通缉结果:

series_id | season | episode
    1          2         1
    2          1         2

我尝试了以下不起作用的查询,可能是因为它首先对其进行分组,然后对结果进行排序。

SELECT      series_id, season, episode
FROM        episodes
GROUP BY    series_id
ORDER BY    season DESC, episode DESC

4 个答案:

答案 0 :(得分:3)

假设每季剧集的数量合理最大(例如,不超过1000集),你可以使用一些数学技巧:

SELECT
    series_id
,   MAX(1000*season + episode)/1000 AS season
,   MAX(1000*season + episode)%1000 as episode
FROM episodes
GROUP BY series_id

我们的想法是构建一个值,其中递增season数字的优先级高于上一季的最高episode,并将这些数字提供给MAX以供选择。在您的示例中,合成数字如下:

id | series_id | season | episode   |  composite
1       1          1         9         1009
2       1          2         1         2001
3       2          1         1         1001
4       2          1         2         1002

我们拥有max后,我们会使用千位数作为季节编号,其余作为剧集编号。

答案 1 :(得分:1)

请勿使用group by。你想要一个过滤器。这是一种方法:

select e.*
from episodes e
where (e.season, e.episode) = (select e2.season, e2.episode
                               from episodes e2
                               where e2.series = e.series
                               order by e2.season desc, e2.episode desc
                               limit 1
                              );

答案 2 :(得分:0)

试试这个

select series_id, max(season) as season, max(episode) as episode 
from your_table
group by series_id

工作样本here

答案 3 :(得分:0)

您可以使用Rank来定义集合中的结果和排名中的过滤器。

SELECT X.* FROM
(Select *, DENSE_RANK() OVER (PARATITION BY ID ORDER BY EPISODE DESC)AS RNK
) AS X
WHERE X.RNK = 1