【问题标题】:SQL antijoin with multiple keys具有多个键的 SQL 反连接
【发布时间】:2021-02-01 16:04:23
【问题描述】:

我想在两个表上实现反连接,但使用两个键,以便结果是表 A 中不包含表 B 中的 [key_1, key_2] 组合的所有行。我该怎么写用 SQL 查询?

【问题讨论】:

  • 这些不是多个“键”而是单个“复合键”。

标签: sql subquery left-join anti-join


【解决方案1】:

如果要反left join,逻辑是:

select a.*
from tablea a 
left join tableb b on b.key_1 = a.key_1 and b.key_2 = a.key_2
where b.key_1 is null

对于我来说,我喜欢用not exists来实现这样的逻辑,因为我发现它更能表达意图:

select a.*
from tablea a
where not exists (
    select 1 from tableb b where b.key_1 = a.key_1 and b.key_2 = a.key_2
)

not exists 查询将利用tableb(key_1, key_2) 上的索引。

【讨论】:

  • 谢谢!需要进行的一个小修改是将最后一行更改为 where b.key_1 is null,但随后它按预期工作。
猜你喜欢
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多