如何基于OR条件从一个表联接到多个表?

时间:2019-04-05 18:30:21

标签: sql

我需要执行以下逻辑。我必须选择t2.demandGroup

IF

t1.localShipToParty = t2.customerId然后t2.demandGroup

ELSE

t1.localShipToParty = t3.kunnr(如果是),然后检查

t3.hkunnr = t2.customerId获取相应记录,如果是,则t2.demandGroup

示例字段:https://www.db-fiddle.com/f/fM9XU115zMux2hkdsLEiz2/0

示例:

    select * from t1;

| localShipToParty |
| ---------------- |
| 123              |
| 0000170249       |
| 783947           |

    select * from t2;

| customerId | demandGroup |
| ---------- | ----------- |
| 123        | grp1        |
| 0000000341 | grp2        |

    select * from t3;

| kunnr      | hkunnr     |
| ---------- | ---------- |
| 0000170249 | 0000000341 |

所需的输出:

| demandGroup |
| ----------- |
| grp1        |
| grp2        |

以下解决方案有效:

select t2.demandGroup
from t1
inner join t2
on t1.localShipToParty = t2.customerId

UNION

select t2.demandGroup
from t1
inner join t3
on t1.localShipToParty = t3.kunnr
inner join t2
on t3.hkunnr = t2.customerId;

我的问题是,是否可以在没有UNION的情况下也可以在没有OR条件的情况下进行上述解决方案?我要求一种比UNION更好的解决方案,因为其余查询的长度约为2000行,并且我想避免使用UNION复制仅粘贴相关部分的内容,以免造成混淆。如果我为UNION复制粘贴,我将获得接近10000行代码。

类似这样的东西

select t2.demandGroup
from t1
( inner join t2
  on t1.localShipToParty = t2.customerId
) OR 
( inner join t3
  on t1.localShipToParty = t3.kunnr
  inner join t2
  on t3.hkunnr = t2.customerId
)

注意:我不是从RDBMS查询,而是从网格查询。因此,我希望与供应商无关的解决方案。另外,DB-Fiddle中的示例是出于说明目的(MySQL 8.0)。

编辑:

根据评论,我尝试使用两个left outer join。但是我没有得到想要的输出。

    select t2.demandGroup as output
    from t1
    left outer join t2
    on t1.localShipToParty = t2.customerId
    left outer join t3
    on t1.localShipToParty = t3.kunnr
    and t3.hkunnr = t2.customerId;

| output |
| ------ |
| grp1   |
|        |
|        |

2 个答案:

答案 0 :(得分:1)

一种方法是使用两个LEFT JOIN操作。对于不匹配的行,外部联接的列中包含空值。

-- select result from t3x or t2
select coalesce(t3x.demandGroup, t2.demandGroup) as demandGroup
from t1
-- if "true", t2 columns contain values
left join t2
on t1.localShipToParty = t2.customerId
-- if "true", t3x columns contain values
left join (
   -- maybe it makes sense to rename for consistency, maybe it doesn't
   select t3.kunnr as customerId, t2.demandGroup
   from t3
   inner join t2
   on t3.hkunnr = t2.customerId) t3x
on t1.localShipToParty = t3x.customerId
where coalesce(t3x.demandGroup, t2.demandGroup) is not null;

答案 1 :(得分:0)

获取结果的可怕方法:)由于笛卡尔先连接然后过滤结果,但这似乎是其中一种方法。

select * from 
(
    select   t1.* ,t2.*,t3.*
    from t2 
    left outer join t1 on 1=1 
    left outer join t3 on 1=1
) 
where demandGroup is not null and (
(localShipToParty=kunnr and hkunnr=customerId) or
(localShipToParty =customerId ))

;