IN运算符不会返回该范围内的所有记录

时间:2018-07-04 13:52:36

标签: mysql sql pdo

我正在尝试返回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))

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

3 个答案:

答案 0 :(得分:4)

我认为您可能想要:

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))

答案 1 :(得分:4)

我猜这个查询就足够了:

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

答案 2 :(得分:3)

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

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)