I'm calling on for MySQL warriors here. 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. 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 :
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.
Any idea on how to achieve this ? Thanks in advance
If I use 1 for My_Team_ID, I get the following results, which shows the remaining matches: