SQL:如何从同一个表中选择两个ID作为两个名称?

时间:2015-05-24 03:55:06

标签: sql postgresql

我是SQL新手并试图处理连接和引用。

数据库看起来像这样:

球员

 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

我已经用Google搜索了一个小时,并且可以找到很多几乎得到我想要的内容,但我仍然无法弄清楚如何用同一个名称替换两个ID表

3 个答案:

答案 0 :(得分:3)

你快到了:

select matches.id, w.name as winner, l.name as loser
 from matches
 join players w on matches.winner = w.id
 join players l on matches.loser = l.id;

答案 1 :(得分:2)

您需要为表名设置别名,以便指定数据应该来自哪个连接。

select
    matches.id,
    p1.name as winner,
    p2.name as loser
from matches
  join players p1 on matches.winner = p1.id
  join players p2 on matches.loser = p2.id;

答案 2 :(得分:0)

您需要确保在该表上加入两次并保持别名正确。

SELECT Matches.id, winner.name, loser.name
From Matches
INNER JOIN Players as winner on winner.id = Matches.winner
INNER JOIN Players as loser on loser.id = Matches.winner;