PostgreSQL查询以从两个表中选择

时间:2018-08-02 16:26:34

标签: postgresql

有两个表A和B。只有在B中不存在的情况下才从A中选择,否则从B中选择。如何在PostgreSQL中编写查询。

表A enter image description here

表B enter image description here

1 个答案:

答案 0 :(得分:1)

这是我想会为您提供的查询。它利用FULL OUTER JOIN并基于将应将两个表关联在一起的4列上的联接,所有其他列(属性,类型,客户,年份)都相同,只有rev_no相同

SELECT 
    COALESCE(tableB.Property, tableA.Property) as Property,
    COALESCE(tableB.Type, tableA.Type) as Type,
    COALESCE(tableB.rev_no, tableA.rev_no) as rev_no,
    COALESCE(tableB.client, tableA.client) as client,
    COALESCE(tableB.year, tableA.year) as year
FROM
    tableA
        FULL OUTER JOIN tableB 
            ON tableA.Property = TableB.Property AND
                tableA.Type = tableB.type AND
                tableA.client = tableB.client AND
                tableA.year = tableB.year