在 SQL Server 2008 中合并两个表

发布于 2024-12-08 13:07:26 字数 110 浏览 1 评论 0原文

我需要问一下有什么方法可以组合两个不同列数的表,例如:

Select a,b,c, from x

 union 

Select d, e from y

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烟火散人牵绊 2024-12-15 13:07:27

你需要做这样的事情

Select a,b,c from x

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

Select d, e, '' as f from y

我使用了''但你可能想使用NULL或0,NULL将兼容所有数据类型,''不会

我也使用UNION ALL而不是UNION,因为它会表现更好,因为它不不必执行排序操作来消除重复,

这里也不需要别名 f,因为顶级查询确定结果集中列的名称

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

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

the alias f is not needed here either because the top query determines the name of the columns in the resultset

世俗缘 2024-12-15 13:07:27

请注意,

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

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

将产生不同的结果,即将使用第一个出现的表中的属性名称。

也许最好明确地重命名第二个表中的列,例如

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

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 i.e. 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 e.g.

select a, b, c from x
union
select d AS a, e AS b, '' as c from y;
审判长 2024-12-15 13:07:27
select col1, col2, col3, col4
from mytable1
union all
select col5, col6, null as col7, '' as col8
from mytable2
select col1, col2, col3, col4
from mytable1
union all
select col5, col6, null as col7, '' as col8
from mytable2
卷耳 2024-12-15 13:07:27
first table 
id
name
second table 
name 
seatno

如果您想加入姓名和名称;在连接查询中使用 ROW_NUMBER 的两个表中都有一些重复的名称!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文