我无法弄清楚如何从第三个表中获取值,从第一个到第二个到第三个参考索引跳转。数据:
Players
Player_ID| Player_Name| ...
1 | Adam Smith | ...
2 | John Doe | ...
Participants
Participant_ID| Event_ID | Player_ID| ...
1 | 1 | 2 | ...
2 | 1 | 1 | ...
Games
Game_ID|Event_ID|White_player (patricipant id)|Black_Player (participant_id)| ...
1 | 1 | 1 | 2 | ...
我基本上想要的是:
Game_ID|Event_ID|White_player (patricipant id)|Black_Player (participant_id)| ...
1 | 1 | John Doe | Adam Smith | ...
但最后我需要像“John Doe vs Adam Smith”这样的字符串。我不想替换表中的值。我不知道我是否应该这样做,或者可能改变我的表结构。
答案 0 :(得分:0)
允许多次加入同一个表。在这种情况下,您需要加入Players
两次,以获取黑色和白色的名称。所以你需要这样的东西:
select g.game_id
, wp.event_id
, p1.player_name
|| ' vs ' ||
p2.player_name as competitors
from games g
join participants wp
on wp.event_id = g.game_id
and wp.participant_id = g.white_player
join players p1
on wp.participant_id = p1.player_id
join participants bp
on bp.event_id = g.game_id
and bp.participant_id = g.black_player
join players p2
on bp.participant_id = p2.player_id
答案 1 :(得分:0)
经过一些修复,我得到了我想要的结果:
select p1.player_name || ' vs ' || p2.player_name as competitors, g.game_id
from games g
join participants_list wp
on wp.event_id = g.event_id
and wp.participant_id = g.white_player
join players p1
on wp.player_id= p1.player_id
join participants_list bp
on bp.event_id = g.event_id
and bp.participant_id = g.black_player
join players p2
on bp.player_id = p2.player_id