在SELECT结果中替换具有相同属性的列

时间:2018-07-23 13:58:56

标签: mysql sql

对不起,标题有些混乱,我不知道该如何表达。

我要解决的问题是,例如,我有2个表,GAMESPLAYERSGAMES具有GAME_IDPLAYER_1_IDPLAYER_2_IDWINNER_PLAYER_IDPLAYERS具有PLAYER_IDPLAYER_NAME。我希望得到一个GAME_IDPLAYER_1_NAMEPLAYER_2_NAMEWINNER_NAME的返回表,从{{1}基本上替换了ID列 }表及其名称

我想我可以这样做,但是看起来太长了:

GAMES

我做对了吗,有没有更好,更有效的方法来解决此问题?

示例:

GAMES表:

select
  GAME_ID,
  PLAYER_1_NAME,
  PLAYER_2_NAME,
  WINNER_NAME
from
  (
    select
      temp2.*,
      PLAYERS.PLAYER_NAME as WINNER_NAME
    from(
        select
          temp1.*,
          PLAYERS.PLAYER_NAME as PLAYER_2_NAME
        from
          (
            select
              GAMES.*,
              PLAYERS.PLAYER_NAME as PLAYER_1_NAME
            from
              GAMES
              inner join PLAYERS on GAMES.PLAYER_1_ID = PLAYERS.PLAYER_ID
          ) temp1
          inner join PLAYERS on temp1.PLAYER_2_ID = PLAYERS.PLAYER_ID
      ) temp2
      inner join PLAYERS on temp2.WINNER_PLAYER_ID = PLAYERS.PLAYER_ID
  )

玩家表:

GAME_ID | PLAYER_1_ID | PLAYER_2_ID | WINNER_PLAYER_ID
1       | 1           | 3           | 3
2       | 2           | 3           | 3
3       | 1           | 3           | 1

预期返回什么:

PLAYER_ID | PLAYER_NAME
1         | Tom
2         | Sam
3         | Lucy

1 个答案:

答案 0 :(得分:2)

据我了解,下面是您的问题的解决方案;

SELECT GAME_ID,
  P1.PLAYER_NAME AS PLAYER_1_NAME,
  P2.PLAYER_NAME AS PLAYER_2_NAME,
  P3.PLAYER_NAME AS WINNER_NAME
FROM GAMES G 
LEFT JOIN PLAYERS P1 ON G.PLAYER_1_ID = P1.PLAYER_ID 
LEFT JOIN PLAYERS P2 ON G.PLAYER_2_ID = P2.PLAYER_ID 
LEFT JOIN PLAYERS P3 ON G.PLAYER_3_ID = P3.PLAYER_ID 

在您共享示例之后,我确定这是正确的结果。