简体   繁体   English

将 2 个不相关的表连接在一起

[英]Joining 2 unrelated tables together

I have just delved into PostgreSQL and am currently trying to practice an unorthodox query whereby I want to join 2 unrelated tables, each with the same number of rows, together such that every row carries the combined columns of both tables.我刚刚深入研究了 PostgreSQL 并且目前正在尝试练习一个非正统的查询,我想将 2 个不相关的表连接在一起,每个表具有相同的行数,这样每一行都包含两个表的组合列。

These are what I have:这些是我所拥有的:

technical table技术

 position | height | technical_id
----------+--------+-------------
 Striker  |   172  |  3
 CAM      |   165  |  4
(2 rows)

footballers table足球运动员

   name   | age |  country  | game_id
----------+-----+-----------+--------
 Pele     |  77 | Brazil    |  1
 Maradona |  65 | Argentina |  2
(2 rows)

What i have tried:我试过的:

SELECT name, '' AS position, null AS height, age, country, game_id, null as technical_id 
from footballers 
UNION 
SELECT '' as name, position, height, null AS age,'' AS country, null as game_id, technical_id 
from technical;

Output: Output:

   name   | position | height | age |  country  | game_id | technical_id
----------+----------+--------+-----+-----------+---------+-------------
          | Striker  |    172 |     |           |         |     3
          | CAM      |    165 |     |           |         |     4
 Maradona |          |        |  65 | Argentina |    2    |
 Pele     |          |        |  77 | Brazil    |    1    |
(4 rows)

What I'm looking for (ideally):我在寻找什么(理想情况下):

   name   | position | height | age |  country  | game_id | technical_id
----------+----------+--------+-----+-----------+---------+-------------
 Pele     | Striker  |   172  |  77 | Brazil    |    1    |     3
 Maradona | CAM      |   165  |  65 | Argentina |    2    |     4
(2 rows)

Please use below query.请使用以下查询。 But its not the right way of designing the schema.但它不是设计模式的正确方法。 You should have a foreign key.你应该有一个外键。

select t1.position,t1.height,t1.technical_id,t2.name,t2.age,t2.country,t2.game_id
from
(select position,height,technical_id, row_number() over(partition by 
position,height,technical_id) as rnk) t1
inner join 
(select name,age,country,game_id, row_number() over(partition by 
name,age,country,game_id) as rnk) t2
on t1.rnk = t2.rnk;

You don't have a column to join on, so you can generate one.您没有要join的列,因此您可以生成一个。 What works is a sequential number generated by row_number() .有效的是由row_number()生成的序列号。 So:所以:

select *
from (select t.*, row_number() over () as sequm
      from technical t
     ) t join
     (select f.*, row_number() over () as sequm
      from footballers f
     ) f
     using (seqnum);

Note: Postgres has extended the syntax of row_number() so it does not require an order by clause.注意:Postgres 扩展了row_number()的语法,因此它不需要order by子句。 The ordering of the rows is arbitrary and might change on different runs of the query.行的顺序是任意的,并且可能会随着查询的不同运行而改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM