选择另一个表中不存在的值

时间:2010-06-04 11:15:07

标签: sql sql-server-2000

我有两张桌子

表A:

ID
1
2
3
4

表B:

ID
1
2
3

我有两个请求:

  • 我想选择表B中没有表B的所有行,在本例中是第4行。
  • 我想删除表B没有的所有行。

我正在使用SQL Server 2000。

6 个答案:

答案 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)

对于您的第一个问题,至少有三种常用方法可供选择:

  • NOT EXISTS
  • 不在
  • LEFT JOIN

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)