我很惭愧地说我的SQL体验很少被使用,当我必须构建一个稍微复杂的查询时,它就会失败,所以我很感激SQL专家的建议。
基本上我有两个表,类似于以下
games(game_id, game_date, player_a_id, player_a_score, player_b_id, player_b_score)
players(player_id, player_name)
我希望构造一个返回相同结果集,玩家名称和分数的查询,即
game_id,game_date,player_a_name,player_a_score,player_b_name,player_b_score
这是我想要优化的天真方法
select games.game_id, games.game_date, (select player_name from players where player_id = games.player_a_id), games.player_a_score, (select player_name from players where player_id = games.player_b_id), games.player_b_score)
有人能告诉我解决这个问题的最佳方法吗?
谢谢!
答案 0 :(得分:3)
也许是这样的:
select
games.game_id,
games.game_date,
pa.player_name as 'player_a_name',
games.player_a_score,
pb.player_name as 'player_b_name',
games.player_b_score
from games
inner join players pa on (games.player_a_id = pa.player_id)
inner join players pb on (games.player_b_id = pb.player_id)
答案 1 :(得分:2)
SELECT
g.game_id, g.game_date,
pa.player_name, g.player_a_score,
pb.player_name, g.player_b_score
FROM games g
LEFT JOIN player pa ON (pa.player_id=g.player_a_id)
LEFT JOIN player pb ON (pb.player_id=g.player_b_id)