如何检查表的一列中的条目是否在另一列中至少出现一次?

时间:2016-05-29 05:33:34

标签: sql sql-server

我有一张看起来像这样的单词表?

CREATE TABLE [dbo].[WordForm] (
    [Word1]  VARCHAR (20) NOT NULL,
    [Word2]  VARCHAR (20) NOT NULL
}

以下是数据的样子?

Word1       Word2
-----       -----
abandon     abandon
abandon     abandonment
adapt       adapt
adapt       adaptable
adapt       adaptation
adapt       adapter
adversely   adverse
adversely   adversely
adversely   adversity

如何检查Word1列中出现的每个单词至少出现在Word2中一次,如果Word1中出现的单词但Word2出现,我需要知道单词是什么。

3 个答案:

答案 0 :(得分:2)

对于大型数据集的更高性能解决方案,请尝试以下方法:

SELECT w.Word1 as [Word 1 Not in Word 2]
FROM   WordForm w
EXCEPT
SELECT w.Word2
FROM   WordForm w
;

SELECT w.Word2 as [Word 2 Not in Word 1]
FROM   WordForm w
EXCEPT
SELECT w.Word1
FROM   WordForm w
;

答案 1 :(得分:1)

SELECT w.Word1 as [Word 1 Not in Word 2]
FROM   WordForm w
WHERE  NOT EXISTS
       (
            SELECT *
            FROM   WordForm x
            WHERE  x.Word2 = w.Word1
       )

SELECT w.Word2 as [Word 2 Not in Word 1]
FROM   WordForm w
WHERE  NOT EXISTS
       (
            SELECT *
            FROM   WordForm x
            WHERE  x.Word1 = w.Word2
       )

答案 2 :(得分:0)

有两个原生运算符,INTERSECTEXCEPT

select word1 from wordform
intersect
select word2 from wordform

select word1 from wordform
except
select word2 from wordform

https://msdn.microsoft.com/en-us/library/ms188055.aspx