简体   繁体   English

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

[英]Reference to outer query in subquery JOIN

I'm calling on for MySQL warriors here. 我在这里呼吁MySQL战士。 My problem is that I need to use a reference to an outer query's table within a left outer join in an subquery. 我的问题是我需要在子查询的左外部联接中使用对外部查询表的引用。 I know this is not possible, but I have no idea on how to replace the subquery filtering with the typical joins in the outer query. 我知道这是不可能的,但是我不知道如何用外部查询中的典型联接替换子查询过滤。

I'll take a typical example to illustrate my issue. 我将以一个典型的例子来说明我的问题。

It's the Olympic games, I have several teams (say table tennis teams) in which there are 1 to N players. 这是奥运会,我有几支球队(比如乒乓球队),其中有1到N名球员。 A match between two teams is finished when all of its players have played against all of the opposing team's players. 当所有队员都与对方球队的所有队员对战时,两队之间的比赛结束。 In brief, I have 3 tables : 简而言之,我有3张桌子:

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

I want to search all players that have disputed none or not every game against all of the opposing team's players (and who are not in my team obviously). 我想搜索所有对所有反对球队的球员(以及显然不在我球队中的球员)没有对每场比赛提出异议的球员。 Here is my query : 这是我的查询:

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
)

I've put a dump for practical purposes : http://pastebin.com/HW3L5ukz I tried to put the 2nd condition of the LEFT OUTER JOIN in the WHERE in the subquery but it doesn't return the proper results. 我出于实际目的放置了转储文件: http : //pastebin.com/HW3L5ukz我试图将LEFT OUTER JOIN的第二个条件放在子查询的WHERE中,但它没有返回正确的结果。

Any idea on how to achieve this ? 关于如何实现这一点的任何想法? Thanks in advance 提前致谢

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

If I use 1 for My_Team_ID, I get the following results, which shows the remaining matches: 如果将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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM