比较2个sql查询中的一对列

时间:2018-01-26 09:56:13

标签: mysql sql

我试图意识到这样的事情:

select column1 column2 from table1 
where column1 and column2 not in (select column1 column2 from table2)

当然这是错误的,但如何正确构建呢?非常感谢你的帮助!

朱莉

4 个答案:

答案 0 :(得分:2)

MySQL支持innot in的元组:

select column1 column2
from table1 
where (column1, column2) not in (select column1 column2 from table2);

那就是说,我更喜欢jarlh的解决方案有两个原因(使用not exists):

  1. 首先,not exists更合理地处理NULL值。
  2. 并非所有数据库都支持innot in的元组。我使用了很多不同的数据库,所以我更喜欢更常用的语法。

答案 1 :(得分:1)

改为使用NOT EXISTS

select column1, column2
from table1 t1
where not exists (select *
                  from table2 t2
                  where t1.column1 = t2.column1
                    and t1.column2 = t2.column2)

答案 2 :(得分:1)

您可以使用LEFT JOINIS NULL,如下所示

select t1.column1, t1.column2 
from table1 t1 
left join table1 t2 ON t2.column1 = t1.column1
    AND t2.column2 = t1.column2
WHERE t2.column1 IS NULL

答案 3 :(得分:0)

你可以使用这样的2个子查询:

select column1, column2 from table1 
where column1 not in (select column1 from table2) 
and column2 not in (select column2 from table2)
相关问题