IN 运算符不返回范围内的所有记录
Posted
技术标签:
【中文标题】IN 运算符不返回范围内的所有记录【英文标题】:IN operator doesn't return all record in the range 【发布时间】:2018-07-04 13:52:35 【问题描述】:我正在尝试返回round
范围内所有可用的matches
,每一轮都可以有不同的匹配。所以我写了这个查询:
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
,为什么其他回合被忽略?
谢谢。
【问题讨论】:
我猜 id 488 的回合有最大的游戏周... @jarlh mmm 但我的目标是为每一轮获得最大游戏周我应该用 OR 替换 IN? 【参考方案1】:我想你可能想要:
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))
【讨论】:
【参考方案2】:我猜这个查询就足够了:
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
s。
【讨论】:
【参考方案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)
【讨论】:
以上是关于IN 运算符不返回范围内的所有记录的主要内容,如果未能解决你的问题,请参考以下文章