将两个不同的查询结果添加到一个表中

时间:2017-12-04 10:03:35

标签: mysql sql sql-server sql-insert rdbms

我有两个不同的查询(结果中有相同的列数)。 我想把它们放在一张桌子里。

例如我有以下表格:

id     country     salary 
1        us        10000

2        uk        25000

3        us        35000

4        uk        31000

5        uk        26000

现在我有以下问题:

查询1:

select * from table where country='us';

查询2:

select * from table where country='uk';

我有一个决赛桌有六列,如:

 id1   |country1  |  salary 1 |  id2  |  country2 |  salary2

现在,我想将两个查询结果放在此表中,以便显示以下输出:

期望的输出:

id1   |country1  |  salary 1  |  id2   |  country2 |  salary2 
 1    |     us   |   10000    |    2   |      uk   |   25000

 3    |     us   |   35000    |    4   |      uk   |   31000

null  |   null   |   null     |    5   |      uk   |   26000

我试过这个,但它没有结合结果:

insert into table (id1,country1,salary1)
select id,country,salary
from table1
where country='us';

insert into table (id2,country2,salary2)
select id,country,salary
from table1
where country='uk';

但它给出了以下结果:

id1   |country1    |  salary 1  |  id2      |  country2   |  salary2 
 1    |     us     |     10000  |     null  |     null    |     null

3     |    us      |    35000   |    null   |    null     |    null

null  |   null     |   null     |   2       |    uk       |    25000

null  |   null     |   null     |   4       |    uk       |    31000

null  |   null     |   null     |   5       |    uk       |    26000

请帮帮我:

1 个答案:

答案 0 :(得分:0)

如果您的DBMS支持窗口起作用,您可以使用它们来适当地加入您的中间结果。

select t1.id, t1.country, t1.salary, t2.id, t2.country, t2.salary
from
(
  select *, row_number() over (order by id) rn
  from data
  where country = 'us'
) t1
full join
(
  select *, row_number() over (order by id) rn
  from data
  where country = 'uk'
) t2 on t1.rn = t2.rn

demo

<强> RESULT

id      country salary  id  country salary
-------------------------------------------
1       us      10000   2   uk      25000
3       us      35000   4   uk      31000
null    null    null    5   uk      26000