zoukankan      html  css  js  c++  java
  • SQLServer两张表筛选相同数据和不同数据

    概述

    项目中经常会对两张数据库表的数据进行比较,选出相同的数据或者不同的数据。在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

    现在要查出两张表相同的数据和两张表不同的数据,如果在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

    如果是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)
  • 相关阅读:
    青岛理工大学邀请赛总结
    HDU 1232 并查集/dfs
    HDU 1556
    HDU 5228
    POJ1011
    线段树(数组实现)
    NOIP2008 普及组T1 ISBN号码 解题报告-S.B.S.
    NOIP2008 普及组T4 立体图 解题报告-S.B.S.(施工未完成)
    noip2008普及组4题题解-rLq
    noip2008普及组3题题解-rLq
  • 原文地址:https://www.cnblogs.com/sunxuchu/p/5433882.html
Copyright © 2011-2022 走看看