2017-02-13 64 views
1

我试图将NOT与WITH在T-SQL中结合使用。但不能让它工作。可能吗?sql-NOT IN结合使用

实施例:

select name 
    from Persons 
    where id NOT IN 
    (
     WITH result (numbers) 
     AS 
     (
      select number from num 
     ) 
     select numbers from result 
    ) 
+2

当返回NULL时的'NOT IN'结果对许多人来说有点令人惊讶。这就是为什么我通常建议使用'NOT EXISTS'来代替。 – jarlh

+1

这是一个练习,或者你可以应用更简单的方法? –

+2

你为什么总是使用'WITH'? – HoneyBadger

回答

4

WITH的关键字不能子查询内使用,它必须是在主查询之前。

WITH result (numbers) 
AS 
(
    select number from num 
) 
select name 
from Persons 
where id NOT IN 
(
    select numbers from result 
) 
0

我知道你已经得到了答案,但只是想展示另一种解决方法,如果有人对未来感兴趣。

SELECT name 
FROM Persons 
WHERE id NOT IN (select number from num)