in运算符不返回范围内的所有记录

vqlkdk9b  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(359)

我想把所有的钱都还给你 matches 在以下范围内提供 round ,每轮可以有不同的匹配。所以我写了这个查询:

SELECT m.id, m.round_id, m.gameweek
 FROM `match` m
 LEFT JOIN competition_rounds r ON m.round_id = r.id
 LEFT JOIN competition_seasons s ON r.season_id = s.id
 LEFT JOIN competition c ON c.id = s.competition_id
 WHERE 1 AND
 m.status = 5 AND
 m.round_id IN (488, 489, 490, 491) AND
 m.gameweek = (SELECT MAX(m2.gameweek)
                FROM `match` m2
                WHERE m2.round_id IN (488, 489, 490, 491))

现在的问题是,结果只返回 matches 在id为488的回合中,为什么其他回合被忽略?谢谢。

lmyy7pcs

lmyy7pcs1#

您需要一个相关的子查询:

SELECT m.id, m.round_id, m.gameweek
 FROM `match` m
 LEFT JOIN competition_rounds r ON m.round_id = r.id
 LEFT JOIN competition_seasons s ON r.season_id = s.id
 LEFT JOIN competition c ON c.id = s.competition_id
 WHERE 1 AND
 m.status = 5 AND
 m.round_id IN (488, 489, 490, 491) AND
 m.gameweek = (SELECT MAX(m2.gameweek)
                FROM `match` m2
                WHERE m2.round_id = m.round_id)
unguejic

unguejic2#

我想你可能想要:

SELECT m.id, m.round_id, m.gameweek
 FROM `match` m
 LEFT JOIN competition_rounds r ON m.round_id = r.id
 LEFT JOIN competition_seasons s ON r.season_id = s.id
 LEFT JOIN competition c ON c.id = s.competition_id
 WHERE 1 AND
 m.status = 5 AND
 m.round_id IN (488, 489, 490, 491) AND
 m.gameweek = (SELECT MAX(m2.gameweek)
                FROM `match` m2
                WHERE m2.round_id = m.round_id))
bf1o4zei

bf1o4zei3#

我猜这个问题已经足够了:

SELECT m.id, m.round_id, m.gameweek
FROM `match` m
WHERE 1 AND
      m.status = 5 AND
      m.round_id IN (488, 489, 490, 491) AND
      m.gameweek = (SELECT MAX(m2.gameweek)
                    FROM `match` m2
                    WHERE m2.round_id = m.round_id AND
                          m2.status = m.status
                   );

也就是说,您可能还需要考虑状态。而且,你不需要 JOIN 除非你真的想在结果中重复。

相关问题