Table1 (id, name) Table2 (id, name)
查询:
SELECT name
FROM table2
-- that are not in table1 already
Table1 (id, name) Table2 (id, name)
查询:
SELECT name
FROM table2
-- that are not in table1 already
当前回答
那对我来说很有用
SELECT *
FROM [dbo].[table1] t1
LEFT JOIN [dbo].[table2] t2 ON t1.[t1_ID] = t2.[t2_ID]
WHERE t2.[t2_ID] IS NULL
其他回答
我没有足够的代表点数来给froadie的答案投票。但我不同意对克里斯回答的评论。以下答案:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
在实践中效率更高。我不知道为什么,但我对800k+的记录进行了运行,上面发布的第二个答案的优势是巨大的。只有我的0.02美元。
以下是对我最有效的方法。
SELECT *
FROM @T1
EXCEPT
SELECT a.*
FROM @T1 a
JOIN @T2 b ON a.ID = b.ID
这比我试过的其他方法快了一倍多。
看到查询:
SELECT * FROM Table1 WHERE
id NOT IN (SELECT
e.id
FROM
Table1 e
INNER JOIN
Table2 s ON e.id = s.id);
从概念上讲是:在子查询中获取匹配的记录,然后在主查询中获取不在子查询中的记录。
这是纯集合论你可以用减号运算来实现。
select id, name from table1
minus
select id, name from table2
小心陷阱。如果表1中的字段Name包含null,你就会感到惊讶。 更好的是:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT ISNULL(name ,'')
FROM table1)