【发布时间】:2017-08-02 00:39:54
【问题描述】:
我的 MySQL 查询有问题。它的子查询没有给出last.id 的最大值。
SELECT rounds.winners, rounds.losers
FROM players
INNER JOIN teams ON teams.id = players.ilmo_id
INNER JOIN status AS first ON first.id = players.status_id
LEFT JOIN matches ON matches.chart_id = 12
AND matches.id = (
SELECT last.id
FROM matches AS last
WHERE (last.player1_id = players.id
OR last.player2_id = players.id
OR last.player3_id = players.id
OR last.player4_id = players.id)
ORDER BY last.id DESC
LIMIT 1
)
JOIN charts ON charts.id = matches.chart_id
JOIN places ON charts.template_id = places.template_id AND places.id = matches.place_id
JOIN templates ON places.template_id = templates.id
JOIN rounds ON places.round_id = rounds.id
WHERE players.comp_id = 12
这个方法我也试过了,但是不行:
SELECT rounds.winners, rounds.losers
FROM players
INNER JOIN teams ON teams.id = players.ilmo_id
INNER JOIN status AS first ON first.id = players.status_id
LEFT JOIN matches ON matches.chart_id = 12
AND matches.id = (
SELECT MAX(last.id)
FROM matches AS last
WHERE (last.player1_id = players.id
OR last.player2_id = players.id
OR last.player3_id = players.id
OR last.player4_id = players.id)
)
JOIN charts ON charts.id = matches.chart_id
JOIN places ON charts.template_id = places.template_id AND places.id = matches.place_id
JOIN templates ON places.template_id = templates.id
JOIN rounds ON places.round_id = rounds.id
WHERE players.comp_id = 12
编辑:
这是最新版本,似乎可以正常工作。
SELECT rounds.winners, rounds.losers
FROM players
INNER JOIN teams ON teams.id = players.ilmo_id
INNER JOIN status AS first ON first.id = players.status_id
LEFT JOIN matches ON matches.chart_id = 12
AND matches.id = (
SELECT last.id
FROM matches AS last
WHERE last.chart_id = 12 /* modified */
AND (last.player1_id = players.id
OR last.player2_id = players.id
OR last.player3_id = players.id
OR last.player4_id = players.id)
ORDER BY last.place_id DESC /* modified */
LIMIT 1
)
JOIN charts ON charts.id = matches.chart_id
JOIN places ON charts.template_id = places.template_id AND places.id = matches.place_id
JOIN templates ON places.template_id = templates.id
JOIN rounds ON places.round_id = rounds.id
WHERE players.comp_id = 12
【问题讨论】:
-
之前几乎可以肯定地问过和回答过数千次,但如果仍然挣扎,请参阅meta.stackoverflow.com/questions/333952/…
-
你要参加什么比赛? on 子句看起来更像是 where 子句的条件。您正在加入匹配,其中chart_id = 12 并且它是最高ID,但在您的子查询中,您没有引用chart_id。它返回所有chart_ids 的最高ID。所以如果最高ID行没有chart_id = 12,on子句将不匹配。
-
@LAS 现在我的子查询有
WHERE last.chart_id = 12 AND (last.player1_id... 好吗? -
是的,我现在明白了。我认为您不需要在 ON 之后立即使用 matches.chart_id = 12。这是多余的,因为它在子查询中处理。
标签: mysql sql database subquery