【问题标题】:not in operator in SQLSQL 中的 not in 运算符
【发布时间】:2017-05-17 18:16:36
【问题描述】:

有两张桌子

table1
ID
1
2
4
6
7

TABLE2
2
4
6

我想要 table1 中不在 table2 中的那些数字,我该怎么做? 我试试这个

select id from table1 t1
inner join table2 t2 on t1.id=t2.id
where t1.id not in (select id from table2) 

但这不起作用

【问题讨论】:

  • 你不必在这里写join
  • SQL NOT IN Clause的可能重复
  • 那么?这个问题与重复问题不同
  • 但这不起作用 -> 你得到了什么结果?或者可能是一个错误?请显示您的输出或错误消息。
  • 我只有标题“ID”

标签: sql sql-server


【解决方案1】:
SELECT t1.id
FROM table1 t1
LEFT JOIN table2 t2 ON t2.id = t1.id
WHERE t2.id IS NULL

从概念上讲,我们从 table1 中选择所有行,并且对于每一行,我们尝试在 table2 中找到与 id 列具有相同值的行。如果没有这样的行,我们只需将该行的结果的 table2 部分留空。然后我们通过仅选择结果中不存在匹配行的那些行来限制我们的选择。最后,我们忽略结果中的所有字段,除了 id 列(我们确定存在的字段,来自 table1)。

【讨论】:

    【解决方案2】:

    试试这个:

    select id from table1 t1 where t1.id not in (select t2.id from table2 t2)
    

    【讨论】:

      【解决方案3】:

      在这种情况下,您不需要连接这两个表。你可以这样做

        select id from table1 A where A.id not in (select B.id from table2 B);
      

      您也可以简单地使用 sql set Difference EXCEPT 运算符来实现此目的

        (select id from table1) except (select id from table2);
      

      【讨论】:

        【解决方案4】:

        使用NOT INNOT EXISTS

        select id from table1 t1
        where t1.id not in (select id from table2) 
        
        
        select id from table1 t1
        where not exists (select id from table2 where id = t1.id) 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-07-11
          • 1970-01-01
          • 1970-01-01
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多