根据最大值获取包含连接的完整行

时间:2015-01-18 16:09:20

标签: mysql subquery max

在mysql中我有这两个表:

**Seasons**
id
number
current

**Episodes**
id
number
season_id
other_info

我想从Episodes得到一整行,Seasons的联接行全部基于两个表的最大number值。

例如,如果我有第1季,第2季,我想从最近的季节获得最新一集。

我从这个问题开始:

SELECT e.id as episode_id, s.id as season_id, MAX(s.number) AS season_number, MAX(e.number) AS episode_number, e.other_info
FROM (episodes AS e)
JOIN seasons AS s ON e.season_id=s.id
WHERE s.current =  1

它有点工作,但它显示错误的other_info值。我理解这是因为MAX()对行进行了分组,但其他值有点随机,所以我认为它只显示了第一行可用的other_info

环顾四周,我发现了我认为可行的这个,但它并没有:

SELECT e.id as episode_id, s.id as season_id, MAX(s.number) AS season_number, MAX(e.number) AS episode_number, e.other_info
FROM (episodes AS e)
JOIN seasons AS s ON e.season_id=s.id
WHERE s.current =  1 AND
e.number = (select max(sube.number) from episodes sube);

在这种情况下,我只获取所有NULL值。

1 个答案:

答案 0 :(得分:1)

我认为这会对你有所帮助:

SELECT seasons.*, episodes.* 
FROM episodes
INNER JOIN seasons ON episodes.season_id = seasons.id
ORDER BY seasons.number DESC ,episodes.number DESC 
limit 0,1