SQL how to compare two columns from two different tables

后端 未结 6 1626
无人共我
无人共我 2021-01-02 16:24

I have two tables, in which table 1 contains 4 columns while table 2 contains 8 columns. I have two columns in table1 that I want to compare them with two columns in table2.

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 16:46

    NOT EXISTS is a "null safe" version of NOT IN. If you mean the combination column1 AND column2 not in same row in table2:

    select *
    from table1
    where NOT EXISTS (select 1 from table2
                      where table1.column1 = table2.column6
                        and table1.column2 = table2.column7)
    

    Or if you mean just column1 and column2 values can't even be in different rows in table2:

    select *
    from table1
    where NOT EXISTS (select 1 from table2
                      where table1.column1 = table2.column6)
      and NOT EXISTS (select 1 from table2
                      where table1.column2 = table2.column7)
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题