您好,欢迎访问一九零五行业门户网

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

项目中经常会对两张数据库表的数据进行比较,选出相同的数据或者不同的数据。在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 allselect 13823400000,56 union allselect 13800056400,88 union allselect 13800230000,28 union allselect 13802300000,18 union allselect 13822220000,68 union allselect 13844400000,98 union allselect 13833330000,35 union allselect 13822220000,31 union allselect 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 allselect 13823400000 union allselect 13800051230 union allselect 13800230123
现在要查出两张表相同的数据和两张表不同的数据,如果在sql server 2005以上版本:--相同数据select tel_no from aintersectselect tel_no from b--不同数据select tel_no from bexceptselect tel_no from a
如果是sql server 2000select * 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)
两张方法得到的结果都是一样的:
其它类似信息

推荐信息