zoukankan      html  css  js  c++  java
  • 你真的会玩SQL吗?EXISTS和IN之间的区别

    你真的会玩SQL吗?EXISTS和IN之间的区别

    EXISTS和IN之间的区别

    1.EXISTS只返回TRUE或FALSE,不会返回UNKNOWN。

    2.IN当遇到包含NULL的情况,那么就会返回UNKNOWN。


    当查询的列包含NULL时,NOT EXISTS正常返回TRUE或FALSE。

    而NOT IN可能返回空集,如下

    1:val IN(val1,val2,...,NULL),永远不会返回FALSE,而是返回TRUE或UNKNOWN。

    2:val NOT IN(val1,val2,...,NULL),永远不会返回TRUE,而是返回NOT TRUE或NOT UNKNOWN。


    看个示例:

    Test1表

    select t.[name] from Test as t

    where  exists (select t1.orderid from Test1 as t1 where t1.[name]=t.[name])

    返回 aaa,ccc,ddd


    select t.[name] from Test as t

    where  t.[name] in  (select t1.[] from Test1 as t1)

    返回 aaa,ccc,ddd


    select t.[name] from Test as t

    where  not exists (select t1.orderid from Test1 as t1 where t1.[name]=t.[name])

    返回 bbb


    select t.[name] from Test as t

    where  t.[name] not in  (select t1.[name] from Test1 as t1)

    返回空集

    练习

    以下对就返回哪三值?

    答案
    View Code

     用例数据库文件 你真的会玩SQL吗?之逻辑查询处理阶段 文末


    custid      companyname
    ----------- ----------------------------------------
    21          Customer KIDPX
    23          Customer WVFAF
    33          Customer FVXPQ
    36          Customer LVJSO
    43          Customer UISOJ
    51          Customer PVDZC
    85          Customer ENQZT
    参考SQL:
    --answer:
    select custid, companyname
    from Sales.Customers as C
    where EXISTS
      (select *
       from Sales.Orders as O
       where O.custid = C.custid
         and O.orderdate >= '20070101'
         and O.orderdate < '20080101')
      and not EXISTS
      (select *
       from Sales.Orders as O
       where O.custid = C.custid
         and O.orderdate >= '20080101'
         and O.orderdate < '20090101');

  • 相关阅读:
    Leetcode Spiral Matrix
    Leetcode Sqrt(x)
    Leetcode Pow(x,n)
    Leetcode Rotate Image
    Leetcode Multiply Strings
    Leetcode Length of Last Word
    Topcoder SRM 626 DIV2 SumOfPower
    Topcoder SRM 626 DIV2 FixedDiceGameDiv2
    Leetcode Largest Rectangle in Histogram
    Leetcode Set Matrix Zeroes
  • 原文地址:https://www.cnblogs.com/amengduo/p/9586987.html
Copyright © 2011-2022 走看看