为什么 PostgreSQL 会抛出“FULL JOIN 仅支持合并连接或哈希连接连接条件”

问题描述 投票:0回答:3

尝试使用这样的 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 结果。

感谢您的帮助。

postgresql join
3个回答
15
投票

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

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
投票

您可以在子查询(或 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
        ;

0
投票

https://www.postgresql.org/message-id/flat/20060313104028.GB6714%40svana.org https://wiki.postgresql.org/wiki/PostgreSQL_vs_SQL_Standard#FULL_OUTER_JOIN_conditions

PostgreSQL 目前将此类条件限制为无需构造显式 UNION 操作即可实现的条件;也就是说,条件必须是可散列的、可合并的或常量。

添加对任意完全连接的支持(这可能需要构建内部连接和两个反连接的 UNION)似乎需要做大量工作才能获得最小的收益。

© www.soinside.com 2019 - 2024. All rights reserved.