具有不同列数的联盟

时间:2013-09-21 11:43:02

标签: sql postgresql

我在第一个表中有三列,第二个表有一列存在于第一个表中,另外两个列我想要添加。

例如:

select  c1 as col1, c2 as col2, c3 as col3
from    Table1
union
select  c1, c4 as col4, c5 as col5
from    Table2

expected Result:

col1,col2,col3,col4,col5

2 个答案:

答案 0 :(得分:12)

只需添加null或您喜欢的任何其他默认值作为静态列

select  c1 as col1, 
        c2 as col2, 
        c3 as col3, 
        null as col4, 
        null as col5
from    Table1
union
select  c1, 
        null, 
        null, 
        c4,
        c5
from    Table2 

答案 1 :(得分:3)

你已经问了这个问题,并得到了答案 - https://stackoverflow.com/questions/18923218/unioning-tables-with-different-number-of-columns/18923250#18923250。是否有可能实际上你需要一个join,而不是工会:

select
    t1.c1 as col1,
    t1.c2 as col2,
    t1.c3 as col3,
    t2.c4 as col4,
    t2.c5 as col5
from Table1 as t1
    inner join Table2 as t2 on t2.col1 = t1.col1