我有两个具有相同列名的表。
示例:
id name id name
------- --------
1 xyz 2 abc
我想要这样的答案
id name
-------
1 xyx
2 abc
如何在不使用join
或union
的情况下获得上述答案?
数据库应该是Postgres或SQL Server
答案 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
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;