简体   繁体   English

在SQL Server 2008中合并两个表

[英]Combine two tables in SQL server 2008

I need to ask something is there any way combine two tables different count of columns like: 我需要问的是,有什么办法可以将两个表合并成不同数量的列:

Select a,b,c, from x

 union 

Select d, e from y

you need to do something like this 你需要做这样的事情

Select a,b,c from x

 union all  -- ALL doesn't filter dups and is faster

Select d, e, '' as f from y

I used '' but you might want to use NULL or 0, NULL will be compatible will all data types, '' will not be 我使用了'',但您可能想使用NULL或0,NULL将与所有数据类型兼容,''则不会

I also used UNION ALL not UNION since it will perform better because it doesn't have to do a sort operation to get rid of dups 我还使用了UNION ALL not UNION,因为它会执行得更好,因为它不必执行排序操作即可消除重复现象

the alias f is not needed here either because the top query determines the name of the columns in the resultset 这里也不需要别名f,因为顶部查询确定结果集中列的名称

Note that 注意

select a, b, c from x
union
select d, e, '' as f from y;

and

select d, e, '' as f from y
union
select a, b, c from x;

will yield different results ie the attribute names from the first-appearing table will be used. 将产生不同的结果,即将使用第一个出现的表中的属性名称。

Perhaps better to be unequivocal by explicitly renaming the columns in the second table eg 明确地重命名第二个表中的列也许更好一点,例如

select a, b, c from x
union
select d AS a, e AS b, '' as c from y;
first table 
id
name
second table 
name 
seatno

if you want to join on name & there are some duplicate names in both table the use ROW_NUMBER in join query! 如果要加入名称,并且两个表中都有重复的名称,请在加入查询中使用ROW_NUMBER!

select col1, col2, col3, col4
from mytable1
union all
select col5, col6, null as col7, '' as col8
from mytable2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM