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

jtw3ybtb  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(473)

抱歉,标题有点混乱,我不知道该怎么说。
我想解决的问题是,例如,我有两个表, GAMES 以及 PLAYERS . GAMESGAME_ID , PLAYER_1_ID , PLAYER_2_ID 以及 WINNER_PLAYER_ID . PLAYERSPLAYER_ID 以及 PLAYER_NAME . 我想得到一张退回的table GAME_ID , PLAYER_1_NAME , PLAYER_2_NAME , WINNER_NAME ,实际上是替换 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

预计退货:

GAME_ID | PLAYER_1_NAME | PLAYER_2_NAME | WINNER_PLAYER_NAME
1       | Tom           | Lucy          | Lucy
2       | Sam           | Lucy          | Lucy
3       | Tom           | Lucy          | Tom
fnatzsnv

fnatzsnv1#

据我所知,解决你问题的办法如下:;

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

在你分享的例子之后,我确信这就是确切的结果。

相关问题