首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

表间对比SQL语句,该如何解决

2012-01-26 
表间对比SQL语句先有2表数据如下表1:ABCDX甲2005001380A乙3202702260A丙2804771960B表2:ABCDX甲3604201060

表间对比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)

热点排行
Bad Request.