1

I have a sql statement as

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')

This above query returns no rows.

However, when I remove the sub query, and just use

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

I get the required rows.

Also, the sub query

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

gives rows of data when executed by itself. Is my syntax for the NOT IN incorrect?

4

4 回答 4

3

这是因为NOT IN (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 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 vs. NOT IN vs. 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“t”指的company是外部查询中的“t”。也就是说,查询正在检查t.name not in (t.name)-- 这总是错误的。子查询需要namefrom 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 回答
1

不知道为什么张贴者接受了错误的答案。是的,查询中有错误,应更改以下内容:

where t.name not in(select t.name from table1

至:

where t.name not in(select t1.name from table1 t1

但是,一旦这样做了,用户的困境仍然是一样的。使用 NOT EXISTS 是一种解决方法,但可以避免真正的问题。真正的解决方案是Taryn发布的解决方案,即在子查询中添加过滤器以排除空值。

于 2021-02-03T19:25:16.557 回答
0

我假设您可能nulltable1. 如果您在 中有nulltable1,那么您将希望null在 WHERE NOT IN 查询中明确排除:

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 回答