如何在同一个表中进行连接(按索引)

时间:2015-03-07 22:23:55

标签: postgresql

我有这张表

Player #1
Player #2 
Player #3 
Player #4 
Player #5 
Player #6 

我必须创建另一个配对视图:

Player #1 | Player #4
Player #2 | Player #5
Player #3 | Player #6

如何使用Postgresql创建此视图?

1 个答案:

答案 0 :(得分:0)

您可以使用CROSS JOIN将表格连接到自身,并提取每个可能的对组合的列表:

SELECT t1.player, t2.player
FROM table t1
CROSS JOIN table t2

要显示每位玩家只能玩一次,您可以将前3名和后3名玩家的两个子查询组合在一起:

SELECT
  UNNEST( ARRAY(
    SELECT player FROM playertable ORDER BY player LIMIT 3
  ) ),
  UNNEST( ARRAY(
    SELECT player FROM playertable ORDER BY player OFFSET 3
  ) );