在SSMS中替代NOT IN

ter*_*rry 3 sql t-sql sql-server

我有这种结构的桌子。我试图找到单词中没有出现的所有唯一ID。如何在MS SQL Server中实现这一目标。

id word
1  hello
2  friends
2  world
3  cat
3  dog
2  country
1  phone
4  eyes
Run Code Online (Sandbox Code Playgroud)

我有一个词表

**List**

phone 
eyes
hair
body
Run Code Online (Sandbox Code Playgroud)

预期产量

除了列表中的单词,我还需要所有唯一的ID。在这种情况下,

2
3
Run Code Online (Sandbox Code Playgroud)


I&4不在输出中,因为它们的单词出现在列表中

我尝试了以下代码

Select count(distinct ID)
from Table1
where word not in ('phone','eyes','hair','body')
Run Code Online (Sandbox Code Playgroud)

我也尝试了不存在也不起作用

Mar*_*ith 8

You can also use GROUP BY

SELECT id
FROM Table1
GROUP BY id 
HAVING MAX(CASE WHEN word IN('phone', 'eyes', 'hair', 'body') THEN 1 ELSE 0 END) = 0
Run Code Online (Sandbox Code Playgroud)


Zoh*_*led 5

One way to do it is to use not exists, where the inner query is linked to the outer query by id and is filtered by the search words.

First, create and populate sample table (Please save us this step in your future questions):

DECLARE @T AS TABLE (
    id int, 
    word varchar(20)
)
INSERT INTO @T VALUES
(1, 'hello'),
(2, 'friends'),
(2, 'world'),
(3, 'cat'),
(3, 'dog'),
(2, 'country'),
(1, 'phone'),
(4, 'eyes')
Run Code Online (Sandbox Code Playgroud)

The query:

SELECT DISTINCT id
FROM @T t0
WHERE NOT EXISTS
(
    SELECT 1
    FROM @T t1
    WHERE word IN('phone', 'eyes', 'hair', 'body')
    AND t0.Id = t1.Id
)
Run Code Online (Sandbox Code Playgroud)

Result:

id
2
3
Run Code Online (Sandbox Code Playgroud)