请问怎样用SQL语句将两个表的内容并起来?

goodsong 2004-09-03 12:04:25
table1
col1 col2
1 2
2 3
table 2
col1 col2 col3
1 2 3
1 2 4
2 3 4
合并后为
col1 col2 col1 col2 col3
1 2 1 2 3
2 3 1 2 4
NULL NULL 2 3 4
即两个表的记录条数不一样多,现在要将两个表合成一张表,不足的地方补上NULL
各位帮帮忙!
...全文
159 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
yesterday2000 2004-09-03
  • 打赏
  • 举报
回复
select
isnull (a.col1,null) as col1,
isnull (a.col2,null) as col2,
isnull (b.col1,null) as col1,
isnull (b.col2,null) as col2,
isnull (b.col3,null) as col3
from #tb1 a full join #tb2 b
on a.xh=b.xh
yesterday2000 2004-09-03
  • 打赏
  • 举报
回复
create table table1 (col1 int,col2 int )

create table table2 (col1 int,col2 int,col3 int)

insert into table1
select 1,2
union
select 2,3

insert into table2
select 1,2,3
union
select 1,2,4
union
select 2,5,8
union
select 3,6,7




select identity(int,1,1) as xh,* into #tb1 from table1
select identity(int,1,1) as xh,* into #tb2 from table2

select a.*,b.* from #tb1 a full join #tb2 b on a.xh=b.xh
goodsong 2004-09-03
  • 打赏
  • 举报
回复
谢谢各位老大!还有一个问题,请看一下
http://community.csdn.net/Expert/topic/3336/3336189.xml?temp=8.512515E-02
马前小卒 2004-09-03
  • 打赏
  • 举报
回复
up
zjcxc 2004-09-03
  • 打赏
  • 举报
回复
--测试

--测试数据
create table table1 (col1 int,col2 int)
insert table1 select 1,2
union all select 2,3

create table table2 (col1 int,col2 int,col3 int)
insert table2 select 1,2,3
union all select 1,2,4
union all select 2,3,4
go

--合并查询
select id=identity(int),col1,col2 into #t1 from table1
select id=identity(int),col1,col2,col3 into #t2 from table2

select a.col1,a.col2
,b.col1,b.col2,b.col3
from #t1 a full join #t2 b
on a.id=b.id

drop table #t1,#t2
go

--删除测试
drop table table1,table2

/*--测试结果

col1 col2 col1 col2 col3
----------- ----------- ----------- ----------- -----------
1 2 1 2 3
2 3 1 2 4
NULL NULL 2 3 4

(所影响的行数为 3 行)
--*/
zjcxc 2004-09-03
  • 打赏
  • 举报
回复
--上面写错了一点

select id=identity(int),col1,col2 into #t1 from table1
select id=identity(int),col1,col2,col3 into #t2 from table2

select a.col1,a.col2
,b.col1,b.col2,b.col3
from #t1 a full join #t2 b
on a.id=b.id

drop table #t1,#t2
zjcxc 2004-09-03
  • 打赏
  • 举报
回复
select id=identity(int),col1,col2 into #t1 from table1
select id=identity(int),col1,col2,col3 into #t2 from table3

select a.col1,a.col2
,b.col1,b.col2,b.col3
from #t1 a full #t2 b
on a.id=b.id

drop table #t1,#t2

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧