我正在尝试获取season.id
的最大日期的match
。
查询是这样的:
SELECT s.id AS season_id,
s.name AS season_name,
s.competition_id AS competition_id
FROM competition_seasons s
INNER JOIN competition_rounds r ON r.season_id = s.id
INNER JOIN `match` m ON m.round_id = r.id
WHERE s.competition_id = 89
AND m.datetime = (SELECT MAX(m.datetime) FROM `match` m WHERE m.round_id = r.id)
GROUP BY s.id
如您所见,我有一个名为competition_seasons
的表,其中包含可用于比赛的所有季节,在此表上,我可以获得比赛的所有信息,在这种情况下,比赛的ID为{{1 }}。
后来我通过表89
获得了本赛季所有可用的rounds
,在competition_rounds
上玩了match
,所以我使用round
在INNER JOIN
上,因为我只需要获取具有match
的{{1}}。
比赛rounds
的回合不同,季节不同,例如:
查询应该返回matches
,因为最后一个赛季的89
和2017/2018
字段说明比赛进行时,match
在比赛中进行季节MAX(m.datetime)
表示日期可以从2017年开始,到2018年结束(因此,在该季节的两年内)。
查询的结果改为2011,这绝对没有意义。
我在查询中做错了什么?
competition_seasons
match
competition_rounds
2017/2018
匹配
| id | name | competition_id
1 2017/2018 89
2 2016/2017 89
3 2015/2016 89
预期结果:season_id = 1,因为此季节的| id | name | season_id
1 First 1
2 Second 1
3 First 2
4 Second 2
5 First 3
的字段|id | datetime | round_id
1 2018-03-08 00:00:0 1
2 2017-09-10 20:30:0 1
3 2017-04-18 15:30:0 3
4 2016-03-08 00:00:0 3
5 2015-04-08 00:00:0 4
6 2015-05-08 00:00:0 5
比上一个季节大。
答案 0 :(得分:1)
我认为ORDER BY
和LIMIT
可以工作:
SELECT s.id AS season_id, s.name AS season_name,
s.competition_id AS competition_id
FROM competition_seasons s INNER JOIN
competition_rounds r
ON r.season_id = s.id INNER JOIN
`match` m
ON m.round_id = r.id
WHERE s.competition_id = 89
ORDER BY m.datetime DESC
LIMIT 1;
答案 1 :(得分:0)
尝试一下:
SELECT s.id AS season_id,
s.name AS season_name,
s.competition_id AS competition_id
FROM competition_seasons s
INNER JOIN competition_rounds r ON r.season_id = s.id
INNER JOIN `match` m ON m.round_id = r.id
WHERE s.competition_id = 89
AND m.datetime = (SELECT MAX(m1.datetime) FROM `match` m1
INNER JOIN competition_rounds r1
ON m1.round_id = r1.id
INNER JOIN competition_seasons s1
ON r1.season_id = s1.id
AND s1.competition_id = 89)