为什么PostgreSQL抛出" FULL JOIN仅支持merge-joinable或hash-joinable join条件"

时间:2017-11-21 05:21:45

标签: postgresql join

尝试使用这样的OR条件连接2个表:

FULL JOIN table1
     ON (replace(split_part(table1.contract_award_number::text, ' '::text, 2), '-'::text, ''::text)) = table2.contract_award_id 

     OR (btrim(replace(table1.solicitation_number::text, '-'::text, ''::text))) = table2.solicitation_id

但是Postgresql正在咆哮着我:

FULL JOIN is only supported with merge-joinable or hash-joinable join conditions

是什么给出的?出于某种原因,如果我添加条件:

WHERE table1.solicitation_number::text ~~ '%%'::text 

错误没有发生,但我怀疑这会导致FULL JOIN结果出现问题。

感谢您的帮助。

2 个答案:

答案 0 :(得分:6)

应该可以使用以下查询模拟两个表之间的任何完全外部联接:

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION ALL
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
WHERE t1.id IS NULL

联合的前半部分获取第一个表独有的记录以及所有重叠记录。工会的后半部分仅获得第二张表的记录。将此模式应用于您的查询会给出:

SELECT column1, column2, column3
FROM fpds_opportunities fpds
LEFT JOIN fbo_all_opportunity_detail fbo
    ON replace(split_part(fbo.contract_award_number::text, ' '::text, 2), 
               '-'::text, ''::text) = fpds.contract_award_id OR
       btrim(replace(fbo.solicitation_number::text, '-'::text, ''::text)) = fpds.solicitation_id
UNION ALL
SELECT column1, column2, column3
FROM fpds_opportunities fpds
RIGHT JOIN fbo_all_opportunity_detail fbo
    ON replace(split_part(fbo.contract_award_number::text, ' '::text, 2), 
               '-'::text, ''::text) = fpds.contract_award_id OR
       btrim(replace(fbo.solicitation_number::text, '-'::text, ''::text)) = fpds.solicitation_id
WHERE
    fpds.contract_award_id IS NULL AND fdps.solicitation_id IS NULL;

答案 1 :(得分:1)

你可以在子查询(或CTE)中预先计算丑陋的字符串,然后用它来加入。 (这对于构建和测试查询似乎也很方便;你从来没有得到这些字符串 - 第一次......)

SELECT ...
FROM table2
FULL JOIN (
        SELECT *
        , replace(split_part(table1.contract_award_number::text, ' '::text, 2), '-'::text, ''::text) AS xca
        , btrim(replace(table1.solicitation_number::text, '-'::text, ''::text)) AS xsa
        FROM table1
        ) AS t1
                ON table2.contract_award_id = t1.xca
                OR table2.solicitation_id = t1.xsa
        ;