日期:2014-05-18  浏览次数:20370 次

表间对比SQL语句
先有2表数据如下
表1:
A           B           C           D               X
甲       200         500       1380         A
乙       320         270       2260         A
丙       280         477       1960         B
表2:
A           B           C           D               X
甲       360         420       1060         A
乙       330         680       1270         A
丁       750         350       820           A

A为关键字段
求几条语句分别达到如下效果:
1、筛选出表1中有而表2中没有的数据
2、筛选出表1、表2中都包含的数据
3、筛选出表2中有表1中没有,且X项为A的数据

------解决方案--------------------
select
t.*
from
表1 t
where
not exists(select 1 from 表2 where A=t.A)

select
t.*
from
表1 t
where
exists(select 1 from 表2 where A=t.A)

select
t.*
from
表2 t
where
t.X= 'A '
and
not exists(select 1 from 表1 where A=t.A)
------解决方案--------------------

create table 表1(A varchar(10), B int, C int, D int, X varchar(10))
insert 表1 select '甲 ', 200, 500, 1380, 'A '
union all select '乙 ', 320, 270, 2260, 'A '
union all select '丙 ', 280, 477, 1960, 'B '

create table 表2(A varchar(10), B int, C int, D int, X varchar(10))
insert 表2 select '甲 ', 360, 420, 1060, 'A '
union all select '乙 ', 330, 680, 1270, 'A '
union all select '丁 ', 750, 350, 820, 'A '

--就是不喜欢和别人一样
--1、筛选出表1中有而表2中没有的数据
select * from 表1 a where
(select count(1) from 表1 left join 表2 on 表1.a <> 表2.a where 表1.a=a.a)
=(select count(1)from 表2)
--2、筛选出表1、表2中都包含的数据
select * from 表1 join 表2 on 表1.a=表2.a
--3、筛选出表2中有表1中没有,且X项为A的数据
select * from 表2 a where
(select count(1) from 表2 left join 表1 on 表2.a <> 表1.a and 表2.x= 'A ' where 表2.a=a.a)
=(select count(1)from 表1)