对不起,标题有些混乱,我不知道该如何表达。
我要解决的问题是,例如,我有2个表,GAMES
和PLAYERS
。 GAMES
具有GAME_ID
,PLAYER_1_ID
,PLAYER_2_ID
和WINNER_PLAYER_ID
。 PLAYERS
具有PLAYER_ID
和PLAYER_NAME
。我希望得到一个GAME_ID
,PLAYER_1_NAME
,PLAYER_2_NAME
,WINNER_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
答案 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
在您共享示例之后,我确定这是正确的结果。