我有两张桌子
表A:
ID
1
2
3
4
表B:
ID
1
2
3
我有两个请求:
我正在使用SQL Server 2000。
答案 0 :(得分:79)
您可以使用NOT IN
:
SELECT A.* FROM A WHERE ID NOT IN(SELECT ID FROM B)
但是,同时我更喜欢NOT EXISTS
:
SELECT A.* FROM A WHERE NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID)
还有其他选择,本文很好地解释了所有优点和缺点:
Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
答案 1 :(得分:25)
对于您的第一个问题,至少有三种常用方法可供选择:
SQL看起来像这样:
SELECT * FROM TableA WHERE NOT EXISTS (
SELECT NULL
FROM TableB
WHERE TableB.ID = TableA.ID
)
SELECT * FROM TableA WHERE ID NOT IN (
SELECT ID FROM TableB
)
SELECT TableA.* FROM TableA
LEFT JOIN TableB
ON TableA.ID = TableB.ID
WHERE TableB.ID IS NULL
根据您使用的数据库,每种数据库的性能可能会有所不同。对于SQL Server(不可为空的列):
NOT EXISTS和NOT IN谓词是搜索缺失值的最佳方法,只要两个列都不是NULL。
答案 2 :(得分:3)
这将在您的案例中选择4
SELECT ID FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
这会删除它们
DELETE FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
答案 3 :(得分:2)
select ID from A where ID not in (select ID from B);
或
select ID from A except select ID from B;
你的第二个问题:
delete from A where ID not in (select ID from B);
答案 4 :(得分:1)
SELECT ID
FROM A
WHERE NOT EXISTS( SELECT 1
FROM B
WHERE B.ID = A.ID
)
答案 5 :(得分:-2)
SELECT ID
FROM A
WHERE ID NOT IN (
SELECT ID
FROM B);
SELECT ID
FROM A a
WHERE NOT EXISTS (
SELECT 1
FROM B b
WHERE b.ID = a.ID)
SELECT a.ID
FROM A a
LEFT OUTER JOIN B b
ON a.ID = b.ID
WHERE b.ID IS NULL
DELETE
FROM A
WHERE ID NOT IN (
SELECT ID
FROM B)