【问题标题】:SQL Join condition - not existing valuesSQL 连接条件 - 不存在值
【发布时间】:2021-02-12 23:03:11
【问题描述】:

我有两个表要加入两个参数。两个表中的第一个参数(名称)需要相同。当表 B 中的名称存在第二个参数(属性)时,我也希望属性匹配。如果表 A 中的属性在表 B 中不存在,我想加入表 B 中的固定值,在本例中为黑色。

Example

我试过这样:

LEFT OUTER JOIN on TableA.name = TableB.name and TableB.attribute = CASE WHEN NOT EXISTS(
     SELECT TableB2.attribute FROM TableB TableB2 WHERE TableB2.attribute = TableA.attribute) 
THEN 'black' ELSE TableA.attribute END

这行得通,但速度很慢,而且我确信有更好的解决方案,因为我是 SQL 新手。

提前致谢:)

【问题讨论】:

  • 请提供样本数据、所需结果和适当的数据库标签。

标签: sql join conditional-statements exists


【解决方案1】:

这种类型的默认设置通常使用两个left joins 来处理:

select . . .,
       colaesce(b.value, bdef.value) as value
from tableA a left join
     tableB b
     on b.attribute = a.attribute left join
     tableB bdef
     on bdef.attribute = 'black'

【讨论】:

  • 谢谢,这就是我要找的 :)
猜你喜欢
  • 2022-01-01
  • 2013-05-18
  • 2014-12-25
  • 2011-03-29
  • 2023-04-10
  • 1970-01-01
  • 2017-07-28
相关资源
最近更新 更多