日期:2014-05-17 浏览次数:20522 次
select id,time,other
from
(
select *,1 as v from Tab_A
union all
select *,2 as v from Tab_B
where not exists(select 1 from Tab_A where Tab_A.id = Tab_B.id)
)t
order by v,time
create table Tab_A (id int,[time] datetime,other nvarchar(10))
insert into Tab_A
select 1,'2013-01-01','A' union all
select 2,'2013-01-02','B' union all
select 3,'2013-01-03','C' union all
select 4,'2013-01-04','D'
create table Tab_B (id int,[time] datetime,other nvarchar(10))
insert into Tab_B
select 2,'2013-01-06','B' union all
select 4,'2013-01-04','C' union all
select 5,'2013-01-01','D'
select *,'A' from Tab_A
UNION ALL
select *,'B' from Tab_B where Tab_B.id not in(select id from Tab_A) order by time
/*
1 2013-01-01 00:00:00.000 A A
2 2013-01-02 00:00:00.000 B A
3 2013-01-03 00:00:00.000 C A
4 2013-01-04 00:00:00.000 D A
5 2013-01-08 00:00:00.000 D B
*/
create table Tab_A (id int,[time] datetime,other nvarchar(10))
insert into Tab_A
select 1,'2013-01-01','A' union all
select 2,'2013-01-02','B' union all
select 3,'2013-01-03','C' union all
select 4,'2013-01-04','D'
create table Tab_B (id int,[time] datetime,other nvarchar(10))
insert into Tab_B
select 2,'2013-01-06','B' union all
select 4,'2013-01-04','C' union all
select 5,'2013-01-01','D'
select *,'A' AS 表 from Tab_A
UNION ALL
select *,'B' from Tab_B where Tab_B.id not in(select id from Tab_A) order by 表,time
/*
1 2013-01-01 00:00:00.000 A A
2 2013-01-02 00:00:00.000 B A
3 2013-01-03 00:00:00.000 C A
4 2013-01-04 00:00:00.000 D A
5 2013-01-01 00:00:00.000 D B
*/