基于条件postgres的联接类型

时间:2018-08-13 01:27:54

标签: sql postgresql

我有2个表,其中基于表A的类型和项目,我想强制存在于另一个表中或不需要它(以返回此ID)

我写了以下内容,但是却出现SQL错误。

如何实现这种行为?

    SELECT
       item.id, delivery
    FROM
       item
    (CASE 
     WHEN item.id not in (select ad_object_id from delivery) THEN 
     LEFT JOIN
       ad_object_delivery 
    ON 
       item.id = ad_object_id
    ELSE 
     JOIN
        ad_object_delivery 
     ON 
        item.id = ad_object_id
     END  
   )  

示例数据:

项目

id | name   | type
1  | John   | socks
2  | Daniel | pants
3  | Barak  | shirt

交付

id | item_id | delivery
1  | 1       | UK
1  | 1       | US

定义

id | item_id | definition
1  | 1       | UK
1  | 2       | IL

我只想得到约翰和巴拉克的记录,因为丹尼尔只出现在交货时,而没有出现在定义中。巴拉克都没出现,所以没事。

3 个答案:

答案 0 :(得分:0)

我认为您想要这样的东西:

SELECT i.id, COALESCE(d.delivery, aod2.delivery)
FROM item i LEFT JOIN
     delivery d
     ON i.id = d.ad_object_id LEFT JOIN
     ad_object_delivery aod2
     ON i.id = aod2.ad_object_id AND d.ad_object_id IS NULL
WHERE d.ad_object_id IS NOT NULL OR aod2.ad_object_id IS NOT NULL;

仅当ad_object_delivery不存在时,它与delivery匹配。请注意,您需要调整SELECT子句以从两个表中选择列。

答案 1 :(得分:0)

如果正确理解,则需要JOINUNION ALL

select i.id, i.name, dl.delivery
from item i inner join
     delivery dl
     on dl.item_id = i.id inner join
     definition df
     on df.item_id = i.id
union all
select i.id, i.name, null
from item i
where not exists (select 1 from delivery dl where dl.item_id = i.id) and
      not exists (select 1 from definition df where df.item_id = i.id);

答案 2 :(得分:0)

一个令人困惑的要求,但我认为是这样的:

select i.*
from item i
left join (select distinct item_id from delivery) del on del.item_id=i.id
left join (select distinct item_id from def) def on def.item_id=i.id
where (del.item_id is null and def.item_id is null)
or (del.item_id is not null and def.item_id is not null)