繁体   English   中英

有条件地连接三个表

[英]Join three tables on condition

我有以下问题:

给定 3 个表:
A 列 id( bigint ), price( integer )
B 列 id( bigint ),卧室( integer )
C 列 id( bigint ),卧室( integer )

我必须通过以下方式将卧室分别从表 B、C 中加入“id”列添加到表 A:
首先根据“id”查找 B 中的卧室。 如果“id”不存在,请查看表 C。如果在 B 和 C 中找不到 id,则排除 A 中的记录。

我将如何得到要求的结果?

create table A(
    id BIGINT,
    price INTEGER
);
create table B(
    id BIGINT,
    bedrooms INTEGER
);
create table C(
    id BIGINT,
    bedrooms INTEGER
);


insert into A(id,price)
    values
        (1,1000),
        (2,1200),
        (3,1600),
        (4,2100),
        (5,1200);

insert into B(id,bedrooms)
    values
        (1,1),
        (2,5),
        (4,2),
        (6,2);


insert into C(id,bedrooms)
    values
        (1,2),
        (3,4),
        (4,3);

select A.id,A.price,
    (case 
        when A.id = B.id then B.bedrooms
        when A.id = C.id then C.bedrooms
    end) as bedrooms
from A 
inner join B on A.id = B.id
inner join C on A.id = C.id
order by A.id

预期输出:

预期产出

我们可以使用id分别对BC表进行LEFT JOIN 现在,我们可以利用COALESCE() ,首先考虑B.bedrooms (如果不为空),否则C.bedrooms 现在,有可能两者都为空(即,两个表中都不存在id )。

在这种情况下,如果您不想要这些行,您可以添加一个额外的WHERE条件来仅考虑那些 id(s),它在BC至少有一个匹配的行。

这是一种方法:

select A.id,
       A.price,
       COALESCE(B.bedrooms, C.bedrooms) AS bedrooms 
from A 
left join B on A.id = B.id
left join C on A.id = C.id
WHERE NOT (B.bedrooms IS NULL AND 
           C.bedrooms IS NULL)
order by A.id

试试这个方法。 使用左连接只会采用那里的值。

select A.id,A.price,
    (case 
        when B.id is not null then B.bedrooms
        when ((B.id is null) and (C.id is not null)) then C.bedrooms
    end) as bedrooms
from A 
left join B on A.id = B.id
left join C on A.id = C.id
order by A.id

试试这个方法。

select R.id, R.price, 
  (case when R.bedrooms is not null then R.bedrooms
    when C.bedrooms is not null then C.bedrooms) as bedrooms  
from (select A.id as id,A.price as price ,B.bedrooms as bedrooms
    from A 
    left join B on A.id = B.id ) as R
inner join C on C.id = R.id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM