SQL帮助:根据两列中的值在一个表中查找第二个表中不存在的行

时间:2010-01-22 19:11:01

标签: sql tsql

我有两张桌子。我试图在一个表中找到基于两列中的值在第二个表中不存在的行。 (我已将表简化为仅包含两列)。两个表之间没有主键/外键。看起来很简单,但我现在有脑袋!

DDL:
CREATE TABLE [dbo].[Table_1](
    [firstname] [nchar](10) NULL,
    [lastname] [nchar](10) NULL
) 

CREATE TABLE [dbo].[Table_2](
    [firstname] [nchar](10) NULL,
    [lastname] [nchar](10) NULL
) 

- 创建样本数据

INSERT INTO [dbo].[Table_1]([firstname], [lastname])
SELECT N'John      ', N'Doe       ' UNION ALL
SELECT N'John      ', N'Smith     '
INSERT INTO [dbo].[Table_2]([firstname], [lastname])
SELECT N'John      ', N'Doe       '

- 我尝试失败了。我期待约翰史密斯回归

SELECT t.* FROM Table_1 AS t
WHERE NOT EXISTS
(SELECT t2.* FROM Table_2 AS t2
WHERE t.firstname <> t2.firstname
AND t.lastname <> t2.lastname)

SELECT * FROM Table_1 AS t
JOIN Table_2 AS t2
ON t.firstname <> t2.firstname
AND t.lastname <> t2.lastname

4 个答案:

答案 0 :(得分:9)

这个怎么样:

SELECT * 
FROM Table_1 AS t1
LEFT OUTER JOIN Table_2 AS t2
ON t1.firstname = t2.firstname
AND t1.lastname = t2.lastname
WHERE t2.firstname IS NULL AND t2.lastname IS NULL

就我而言,我只回到约翰史密斯那里。

您基本上在公共字段的表格之间执行外部联接 - 两种情况下都存在的行将包含t1t2的值。< / p>

t1中仅显示的行不会包含第二个表t2的任何值。

答案 1 :(得分:2)

我认为这应该有效:

SELECT t.* FROM Table_1 AS t
 LEFT JOIN Table_2 t2 ON (t.firstname = t2.firstname AND t.lastname = t2.lastname)
WHERE t2.firstname IS NULL AND t2.lastname IS NULL

但我很惊讶你的第一次尝试不起作用:

SELECT t.* FROM Table_1 AS t
WHERE NOT EXISTS
(SELECT t2.* FROM Table_2 AS t2
WHERE t.firstname <> t2.firstname
AND t.lastname <> t2.lastname)

答案 2 :(得分:0)

您可以使用ON子句中的两个列尝试左外连接。

然后使用WHERE子句过滤掉两个表匹配的任何内容

SELECT * FROM table_1 AS one
LEFT OUTER JOIN table_2 AS two
ON one.firstname = two.firstname
AND one.lastname = two.lastname
WHERE two.firstname IS NULL AND two.lastname IS NULL

答案 3 :(得分:0)

外连接很好,但我发现这种方法通常可以在大量数据上执行得更快。

SELECT * 
FROM Table_1 AS t1
WHERE NOT EXISTS
    (
        SELECT *
        FROM Table_2 AS t2
        WHERE t1.firstname = t2.firstname
            AND t1.lastname = t2.lastname
    )