22,209
社区成员
发帖
与我相关
我的任务
分享
create table Table1(cid int,cname varchar(1))
insert Table1
select 1,'a' union all
select 2,'b' union all
select 3,'c'
if object_id('Table2') is not null drop table Table2
go
create table Table2(id int,name varchar(10),cid int)
insert Table2
select 1,1111,1 union all
select 2,2222,2 union all
select 3,3333,3 union all
select 4,4444,2
select id , cname from
(
select id = 0 , cname , cid from table1
union all
select id ,cname = ' ' + name , cid from table2
) t
order by cid
drop table table1, table2
/*
id cname
----------- ------------
0 a
1 1111
2 2222
0 b
4 4444
0 c
3 3333
(所影响的行数为 7 行)
*/
---查询---
select id,cname from (
select 0 as id,cname,cid from [Table1]
union all
select id,name,cid from [Table2])t
order by cid,id
---结果---
id cname
----------- ----------
0 a
1 1111
0 b
2 2222
4 4444
0 c
3 3333
(所影响的行数为 7 行)
select id,cname from (
select 0 as id,cname,cid from [Table1]
union all
select id,' '+name,cid from [Table2])t
order by cid
---测试数据---
if object_id('[Table1]') is not null drop table [Table1]
go
create table [Table1]([cid] int,[cname] varchar(1))
insert [Table1]
select 1,'a' union all
select 2,'b' union all
select 3,'c'
if object_id('[Table2]') is not null drop table [Table2]
go
create table [Table2]([id] int,[name] varchar(10),[cid] int)
insert [Table2]
select 1,1111,1 union all
select 2,2222,2 union all
select 3,3333,3 union all
select 4,4444,2
---查询---
select id,cname from (
select 0 as id,cname,cid from [Table1]
union all
select id,name,cid from [Table2])t
order by cid
---结果---
id cname
----------- ----------
0 a
1 1111
2 2222
0 b
4 4444
0 c
3 3333
(所影响的行数为 7 行)