我是新来的SQL,并试图获得连接和引用的句柄。SQL:如何从同一个表中选择两个ID作为两个名称?
数据库是这样的:
玩家
id | name
----+-------
1 | john
2 | tim
3 | frank
4 | tony
5 | mark
匹配
id | winner | loser
----+--------+-------
1 | 2 | 4
2 | 3 | 4
3 | 4 | 5
4 | 1 | 4
我想要得到这样的结果:
id | winner | loser
----+--------+-------
1 | tim | tony
2 | frank | tony
3 | tony | mark
4 | john | tony
到目前为止,我可以这样做:
select matches.id, players.name as winner, players.name as loser
from matches, players
where winner = players.id;
但是,如果我添加and loser = players.id
,它不返回行。
我也试过这样:
select matches.id, players.name as winner, players.name as loser
from matches
join players on matches.winner = players.id
join players on matches.loser = players.id;
产生ERROR: table name "players" specified more than once
。
我把这个搜索了一个小时,可以找到很多的案例,几乎得到我想要的,但我仍然无法弄清楚如何用同一个表中的两个名称替换两个ID。
谢谢,它的工作原理。我不知道可以在变量'w'和'l'之后放置'players'的特性。有没有一个名称,所以我可以查看它并了解更多信息? – sebu
它被称为别名,用于区分表格并缩短您的语句。 – Tim3880