4

我在第一个表中有三列,第二个表中有一个列存在于第一个表中,我想添加 2。

前任:

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
4

2 回答 2

13

只需添加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 
于 2013-09-21T11:44:40.207 回答
3

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

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
于 2013-09-21T14:10:36.433 回答