我在第一个表中有三列,第二个表中有一列存在于第一个表中,我想添加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
我在第一个表中有三列,第二个表中有一列存在于第一个表中,我想添加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
只需添加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
这回答了所问的问题,但显然不是OP正在追问的问题。看到以前的尝试在这里了解:http://stackoverflow.com/questions/18923218/unioning-tables-with-different-number-of-columns/18923250 – IMSoP
你已经问这个问题,并得到了答案 - 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
我开始认为这是基于OP的意见的答案上次。它表明了在问题中包含正确的细节的重要性,因为UNION这个词完全导致了我们的错误方向,并且没有例子使得纠正几乎是不可能的。 – IMSoP
你能不能给我们的样本数据和输出?这里有几种不同的选择(除了你的问题正在朝着这个方向发展)。例如,你想把第一部分和第二部分的行关联起来吗?或者是不相关的? –
@ Clockwork-Muse显然不是;这个问题[已经被问过一次](http://stackoverflow.com/questions/18923218/unioning-tables-with-different-number-of-columns/18923250)和5次试图请求样本数据被忽略。 – IMSoP