有条件地联接三个表

时间:2019-06-25 12:33:53

标签: mysql

我有以下问题:

给出3个表:
 带有列id(bigint),price(整数)的A
 B的列id(bigint),bedrooms(integer)
 具有列id(bigint),bedrooms(integer)的C

我必须通过以下方式分别将连接表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

预期输出:

Expected Output

3 个答案:

答案 0 :(得分:1)

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

在这种情况下,如果您不想要这些行,则可以放置一个附加的WHERE条件来仅考虑那些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

答案 1 :(得分:0)

尝试这种方式。使用左联接将仅采用其中的值。

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

答案 2 :(得分:0)

尝试这种方法。

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