Home > Database > Mysql Tutorial > body text

两张表筛选相同数据和不同数据

WBOY
Release: 2016-06-07 15:54:28
Original
1599 people have browsed it

项目中经常会对两张数据库表的数据进行比较,选出相同的数据或者不同的数据。在SQL SERVER 2000中只能用Exists来判断,到了SQL SERVER 2005以后可以采用EXCEPT和INTERSECT运算符比较两张表的数据。 EXCEPT运算符返回由EXCEPT运算符左侧的查询返回、而又不包

项目中经常会对两张数据库表的数据进行比较,选出相同的数据或者不同的数据。在SQL SERVER 2000中只能用Exists来判断,到了SQL SERVER 2005以后可以采用EXCEPT和INTERSECT运算符比较两张表的数据。

EXCEPT运算符返回由EXCEPT运算符左侧的查询返回、而又不包含在右侧查询所返回的值中的所有非重复值。

INTERSECT返回由INTERSECT运算符左侧和右侧的查询都返回的所有非重复值。

例如有表A和B,其建表和数据脚本如下:

if object_id('[a]') is not null drop table [a]
go 
create table [a]([tel_no] bigint,[cost] int)
insert [a]
select 13800000000,38 union all
select 13823400000,56 union all
select 13800056400,88 union all
select 13800230000,28 union all
select 13802300000,18 union all
select 13822220000,68 union all
select 13844400000,98 union all
select 13833330000,35 union all
select 13822220000,31 union all
select 13811110000,32
--> 测试数据:[b]
if object_id('[b]') is not null drop table [b]
go 
create table [b]([tel_no] bigint)
insert [b]
select 13800000000 union all
select 13823400000 union all
select 13800051230 union all
select 13800230123
Copy after login
现在要查出两张表相同的数据和两张表不同的数据,如果在SQL SERVER 2005以上版本:
--相同数据
select tel_no  
from a
intersect
select tel_no 
from b

--不同数据
select tel_no  
from b
except
select tel_no 
from a
Copy after login
如果是SQL SERVER 2000
SELECT * FROM b WHERE EXISTS(SELECT 1 FROM a WHERE tel_no=b.tel_no)
 
SELECT * FROM b WHERE NOT EXISTS(SELECT 1 FROM a WHERE tel_no=b.tel_no)
Copy after login
两张方法得到的结果都是一样的:

\

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!