1

次のSQLステートメントがあります

select t.name, t.company from company t inner join employee e
on t.id = e.emp_id
where t.name not in(select t.name from table1 where t.id='x')

上記のクエリは行を返しません。

ただし、サブクエリを削除して使用すると

select t.name, t.company from company t inner join employee e
    on t.id = e.emp_id  

必要な行を取得します。

また、サブクエリ

select t.name from table1 where t.id='x'

単独で実行すると、データ行が得られます。私の構文はNOT IN間違っていますか?

4

4 に答える 4

3

これはNOT IN (NULL)常にfalseであるためです

select t.name, t.company from company t inner join employee e
on t.id = e.emp_id
where t.name not in(select null from dual)

同じだろう。

NOT EXISTS代わりに使用してください:

select t.name, t.company 
from company t 
    join employee e on t.id = e.emp_id
where 
    not exists(select 1 from table1 t2 where t.name = t2.name)
and t.id='x' 

フォローアップ: NOT EXISTS と NOT IN と LEFT JOIN WHERE IS NULL の違いは何ですか?

于 2013-06-17T14:42:32.427 に答える
1

一般的な原因はNULL、サブクエリの値です。しかし、別の問題があります。クエリは次のとおりです。

select t.name, t.company
from company t inner join employee e
     on t.id = e.emp_id
where t.name not in(select t.name from table1 where t.id='x')

t.nameサブクエリの は、company外側のクエリの "t" を参照します。つまり、クエリはt.name not in (t.name)-- をチェックしていますが、これは常に false です。サブクエリには from が必要nameです table1。エイリアスを使用しないと、次のように修正されます。

select t.name, t.company
from company t inner join employee e
     on t.id = e.emp_id
where t.name not in(select name from table1 where id='x')

さらに良いことに、どこでも意味のあるエイリアス (テーブル名の省略形) を使用します。

select c.name, c.company
from company c inner join employee e
     on c.id = e.emp_id
where c.name not in (select t1.name from table1 t1 where t1.id = 'x')
于 2013-06-17T14:41:27.173 に答える
0

nullに値がある可能性があると想定していますtable1nullに値がある場合は、WHERE NOT IN クエリでtable1明示的に除外する必要があります。null

select t.name, t.company 
from company t 
inner join employee e
  on t.id = e.emp_id
where t.name not in(select name 
                    from table1 
                    where id='x'
                       and name is not null);

また、句クエリt.からエイリアスを削除したこともわかります。WHERE外部表に関連付けられた別名を使用していますcompany。エイリアス名を変更するか、削除する必要があります。

于 2013-06-17T14:41:43.723 に答える