【问题标题】:add two different queries result into one table将两个不同的查询结果添加到一张表中
【发布时间】:2017-12-04 10:03:35
【问题描述】:

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

例如我有下表:

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

请帮帮我:

【问题讨论】:

  • 您可以使用连接将它们添加到一个插入语句而不是两个插入语句中
  • 怎么样?我不知道如何在插入语句中使用连接。
  • 添加您正在使用的 DBMS 的标签
  • 这是什么样的桌子设计? .在一行中存储两条不同的记录有什么意义?

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


【解决方案1】:

如果您的 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

结果

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
相关资源
最近更新 更多