我有两个不同的查询(结果中具有相同的列数)。 我想将两者放在一张表中。
例如我有下表:
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';
我有一个决赛 table ,有六列,例如:
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 支持窗口函数,您可以使用它们来适本地连接中间结果。
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
结果
id country salary id country salary
-------------------------------------------
1 us 10000 2 uk 25000
3 us 35000 4 uk 31000
null null null 5 uk 26000
关于mysql - 将两个不同的查询结果添加到一张表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47630801/