LEFT JOIN多次同桌

时间:2016-01-22 16:40:06

标签: sql select join

我有以下数据库架构:

玩家表:

| player_id | 
|-----------|
|     1     |   
|     2     |  
|     3     |   
|     4     |
|    ...    |

游戏桌:

| game_id  | white_player_id | black_player_id | game_status | 
|----------|-----------------|-----------------|-------------|
|    1     |        1        |        2        | in progress |    
|    2     |        3        |        4        | in progress | 
|    3     |        5        |        6        |  white won  | 
|    4     |        1        |        3        |     draw    | 
|   ...    |       ...       |       ...       |     ...     |

我想选择目前没有参加比赛的所有球员。

我试图通过以下方式实现它,但它不能像我期望的那样工作。

SELECT player.player_id
FROM players
LEFT JOIN games g1
  ON players.player_id = g1.white_player_id
LEFT JOIN games g2
  ON players.player_id = g2.black_player_id
WHERE 
  g1.white_player_id IS NULL AND
  g1.game_status NOT IN ('in progress') OR
  g2.white_player_id IS NULL AND
  g2.game_status NOT IN ('in progress')

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT player_id
FROM players
WHERE player_id NOT IN (
   SELECT white_player_id
   FROM games
   WHERE game_status IN ('in progress')

   UNION ALL

   SELECT black_player_id
   FROM games
   WHERE game_status IN ('in progress'))

此查询会选择所有未参加game_status等于'in progress'的游戏的玩家。

答案 1 :(得分:0)

执行此操作时:

  compile 'org.eclipse.jetty.websocket:javax-websocket-client-impl:9.3.6.v20151106'
  compile 'org.eclipse.jetty.websocket:websocket-common:9.1.0.v20131115'

您有效地将左连接转换为内连接。要在外部联接表上进行筛选,请在from子句中执行此操作。

select *
from t1 left join t2 on something
WHERE t2.someField = someValue
AND other conditions