在子查询JOIN中引用外部查询

时间:2012-08-02 14:01:02

标签: mysql join subquery

我在这里呼唤MySQL战士。我的问题是我需要在子查询的左外连接中使用外部查询表的引用。 我知道这是不可能的,但我不知道如何用外部查询中的典型连接替换子查询过滤。

我将举一个典型的例子来说明我的问题。

这是奥运会,我有几支球队(比如乒乓球队),其中有1到N名球员。 当所有球员都对阵所有对方球队的球员时,两队之间的比赛结束。 简而言之,我有3个表:

Team (id, country); 
Player (id, team_id, name) 
Game (id, playerA_id, playerB_id).

我希望搜索所有对抗所有对方球队球员(并且显然不在我的球队中)的球员。 这是我的疑问:

SELECT t.*, p.*
FROM player p
INNER JOIN team t ON t.id = p.team_id AND t.id != My_Team_ID
WHERE EXISTS (
    -- If an opposing team's player has played no game => game.id is NULL
    -- If he hasn't played against all of my teammates => there will be at least one row where game.id is NULL
    SELECT *
    FROM player
    INNER JOIN team ON team.id = player.team_id AND team.id = My_Team_ID
    LEFT OUTER JOIN game ON player.id IN (game.playerA_id, game.playerB_id) AND p.id IN (game.playerA_id, game.playerB_id)
    WHERE game.id IS NULL
)

我为实际目的放了一个转储:http://pastebin.com/HW3L5ukz 我试图在子查询的WHERE中放置LEFT OUTER JOIN的第二个条件,但是它没有返回正确的结果。

有关如何实现这一目标的任何想法? 提前致谢

1 个答案:

答案 0 :(得分:1)

SELECT p1.*, p2.*
FROM player p1
JOIN team t1
  ON t1.id = p1.team_id AND t1.id = My_Team_ID
LEFT JOIN player p2
  ON p2.id != p1.id
JOIN team t2
  ON t2.id = p2.team_id AND t2.id != My_Team_ID
LEFT JOIN game g1
  ON (g1.playerA_id = p1.id OR g1.playerB_id = p1.id)
  AND (g1.playerA_id = p2.id OR g1.playerB_id = p2.id)
WHERE g1.id IS NULL

如果我使用1作为My_Team_ID,我会得到以下结果,其中显示了剩余的匹配项:

id  team_id name            id  team_id     name
1   1       Laurent Dupuis  6   2           Alec Russell
2   1       Stéphane Leroy  6   2           Alec Russell
3   1       Julien le Guen  4   2           Mark Johnsson
3   1       Julien le Guen  6   2           Alec Russell