【问题标题】:HOW TO JOIN TWO TABLES WITH 2 FIELDS [closed]如何连接两个具有 2 个字段的表 [关闭]
【发布时间】:2021-02-06 10:25:25
【问题描述】:

我想通过将 A 和 B 与填充字段连接起来从表 B 中获取 VAL,例如:

一个

F1,F2,F3
1,2,t1
2,3,t2

B

F1,F2,VAL
1,NULL,v1
NULL,2,v2

输出:

1,2,t1,v1
2,3,t2,v2

【问题讨论】:

  • 请解释你想要的逻辑。

标签: sql oracle left-join inner-join


【解决方案1】:

这是你想要的吗?

select a.*, b.val
from a
inner join b
    on (b.f1 is not null and b.f1 = a.f1)
    or (b.f2 is not null and b.f2 = a.f2)

或者:

select a.*, b.val
from a
inner join b 
    on  (b.f1 is null or b.f1 = a.f1)
    and (b.f2 is null or b.f2 = a.f2)

【讨论】:

    【解决方案2】:

    你可以加入or:

    select a.*, b.val
    from a inner join
         b
         on b.f1 = a.f1 or b.f2 = a.f2;
    

    这通常性能很差。另一种选择是两个left joins:

    select a.*, coalesce(b1.val, b2.val)
    from a left join
         b b1
         on b1.f1 = a.f1 left join
         b b2
         on b2.f2 = a.f2 and b1.f1 is null;
    

    【讨论】:

    • 嗨@Gordon Linoff,我还有一个问题,可以获取每个填充字段的最后一个日期事件吗?
    • @JamalMarouf 。 . .您应该提出一个新的问题,并提供适当的解释、示例数据和期望的结果。
    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2017-07-23
    • 2019-10-25
    • 1970-01-01
    • 2015-10-06
    • 2011-05-17
    • 1970-01-01
    相关资源
    最近更新 更多