在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值。
答案 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