如何在不使用join和union的情况下合并两个表?

时间:2015-12-08 10:13:11

标签: sql-server postgresql

我有两个具有相同列名的表。

示例:

id name         id name
-------         --------
1  xyz          2  abc

我想要这样的答案

id name
-------
1  xyx
2  abc

如何在不使用joinunion的情况下获得上述答案?

数据库应该是Postgres或SQL Server

1 个答案:

答案 0 :(得分:0)

在PostgreSQL中

SELECT unnest(ids) id
      ,unnest(vals) "name"
FROM (
    SELECT string_to_array(a.id || ',' || b.id, ',') ids
          ,string_to_array(a.val || ',' || b.val, ',') vals
    FROM a,b
    ) t

简化版:

select unnest(array[a.id,b.id]) id
      ,unnest(array[a.val,b.val]) "name"
from a,b

使用CTE

with cte as(
select * from a
),cte1 as(
select * from b
)
select * from cte
union
select * from cte1 order by id

根据Giorgos Betsos's comment

drop table  if exists t;
create temp table t as  select id,val from a;
insert into t select id,val from b;
select * from t;
相关问题