0

ここで私の質問に対する最良の答えを見つけました: NOT IN 句と NULL 値

次の 2 つのクエリはどちらも結果を返しません。

select upc 
from   staging..posrecords 
where  upc not in (select upc from mrs..items)

select upc 
from   staging..posrecords 
where  upc in (select upc from mrs..items)

次のクエリはどちらも結果を返します。

select upc from staging..posrecords

select upc from mrs..items

後者の 2 つのクエリが両方とも結果を返すことを考えると、最初の 2 つのクエリのどちらも結果をまったく返さない可能性があることを理解できません。たぶん手遅れで、本当に明白な何かが欠けているだけかもしれませんが、私は今できる限り困惑しています.

さらに、次のクエリも結果を返します

select upc 
from mrs..items 
where upc not in (select upc from staging..posrecords)

その場合、上記の最初のクエリが結果を返さない理由について、さらに困惑しています。

4

2 に答える 2

3

理由: サブクエリの列に NULL 値が含まれている場合、常に NULL が返されます。

1 OR 2 OR NULL
TRUE OR NULL
NULL

例を含む詳細。

http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/

に NULL 値がある可能性がありupc column in mrs...items tableます。次のクエリを試してください。

    select upc 
    from   staging..posrecords 
    where  upc not in (select upc from mrs..items where upc is not null)

    select upc 
    from   staging..posrecords 
    where  upc in (select upc from mrs..items where upc is not null)

使ってみてNot exists

    select upc 
    from staging..posrecords 
    where not exists ( select upc from mrs..items 
    where mrs..items.ups = staging..posrecords.upc)


    select upc 
    from   staging..posrecords 
    where not exists(select upc from mrs..items 
    where mrs..items.upc=staging..posrecords.upc)
于 2012-06-07T05:39:18.717 に答える
1

多分それはあなたの悪い日です。代わりに JOIN を使用して、最初の NOT IN クエリを取得してみてください。このような -

SELECT sp.upc 
FROM staging..posrecords sp LEFT JOIN mrs..items mi 
 ON (sp.upc=mi.upc)
WHERE
 mi.upc IS NULL;
于 2012-06-07T05:49:55.967 に答える