• sql中exists,Intersect ,union 与union All的用法


    熟练使用SQL Server中的各种用法会给查询带来很多方便。今天就介绍一下EXCEPT和INTERSECT。注意此语法仅在SQL Server 2005及以上版本支持。

    EXCEPT是指在第一个集合中存在,但是不存在于第二个集合中的数据。  

    就是两个集中不重复的部分。例如
    SELECT * FROM A
    EXCEPT
    SELECT * FROM B
    这个的意思是,凡是不出现在B表中的A表的行

    INTERSECT是指在两个集合中都存在的数据。

    就是两个集中共同的部分。例如
    SELECT * FROM A
    INTERSECT
    SELECT * FROM B
    这个的意思是,同时出现在A和B中的记录

    测试如下:

    [c-sharp] view plain copy
    1. create table t1(id int,mark char(2))  
    2. go  
    3. create table t2(id int,mark char(2))  
    4. go  
    5. insert into t1  
    6.     select 1,'t1' union all  
    7.     select 2,'t2' union all  
    8.     select 3,'t3' union all  
    9.     select 4,'t4'  
    10. go  
    11. insert into t2  
    12.     select 2,'t2' union all  
    13.     select 3,'m3' union all  
    14.     select 5,'m5' union all  
    15.     select 6,'t6'  
    16. go  
    17. select * from t1  
    18. EXCEPT  
    19. select * from t2  
    20. go  
    21. select * from t1  
    22. INTERSECT  
    23. select * from t2  
    24. go  
    25.   
    26. --EXCEPT结果集为  
    27. --1 t1  
    28. --3 t3  
    29. --4 t4  
    30.   
    31. --INTERSECT结果集为  
    32. --2 t2  

     

     

    union 与union All的区别

    --并集UNION
    --UNION与UNION ALL的区别是: union会删除重复值,也就是说A和B中重复的行,最终只会出现一次,而union all则会保留重复行。
    SELECT * FROM t1
     UNION
     SELECT * FROM t2
     
    SELECT * FROM t1
     UNION  all
     SELECT * FROM t2

  • 相关阅读:
    ehcache 使用
    android 换肤 apk
    ant 打不同渠道包
    strawberry perl
    rest 网络设计开发,降低复杂性设计方案
    android 进度条
    android 算定义布局xml
    ant 自动打包
    c# 调用cmd 输出 阻塞 解决
    web service2
  • 原文地址:https://www.cnblogs.com/panmy/p/5152989.html
Copyright © 2020-2023  润新知