gpt4 book ai didi

mysql - 子查询未返回预期结果

转载 作者:行者123 更新时间:2023-11-29 10:09:57 26 4
gpt4 key购买 nike

我正在尝试获取 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 为 89 。后来我得到了所有的rounds通过表格可获取该赛季的比赛信息competition_rounds ,一个matchround 上播放,所以我使用 INNER JOIN关于match表,因为我只需要获取 roundsmatches .

比赛89不同的赛季有不同的轮次,赛季例如:

  • 2017/2018
  • 2016/2017
  • 2015/2016

查询应返回2017/2018因为是最后一季,有 matchMAX(m.datetime)该字段指示比赛何时进行, match参加本赛季2017/2018意味着日期可以从 2017 年开始到 2018 年结束(因此在赛季的两年内)。

查询的结果是 2011,这完全没有意义。

我在查询中做错了什么?

competition_seasons

| id | name       | competition_id
1 2017/2018 89
2 2016/2017 89
3 2015/2016 89

competition_rounds

| 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

预期结果:season_id = 1,因为 match本赛季有场datetime比前几季都要多。

最佳答案

我认为 ORDER BYLIMIT 会起作用:

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;

关于mysql - 子查询未返回预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51179767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com