4

我已经定义了这个表:

CREATE TABLE market.price_history (
    item_id bigint NOT NULL,
    valid_time tstzrange DEFAULT tstzrange(now(), 'infinity'),
    sale_price money NOT NULL,
    promo_code bool NOT NULL DEFAULT false,
    EXCLUDE USING gist(item_id WITH =, valid_time WITH &&),
    EXCLUDE USING gist(item_id WITH =, sale_price WITH =, valid_time WITH &&)
);

但是当我执行这个 SQL 时:

WITH new_row_valid_time as(
    SELECT tstzrange(MAX(upper(valid_time)), 
                     'infinity'::timestamptz) as adjacent_valid_time 
    FROM market.price_history 
    WHERE item_id = 11
)
INSERT INTO market.price_history as ph
(item_id, valid_time, sale_price, promo_code)
VALUES(11,                        -- same id as existent row
       (SELECT adjacent_valid_time 
        FROM new_row_valid_time), -- adjacent range for existent row
       11.83,                     -- same price as the existent row
       False)
ON CONFLICT (item_id, sale_price, valid_time) DO
UPDATE SET valid_time = tstzrange(lower(ph.valid_time), 'infinity'::timestamptz)
WHERE ph.item_id = excluded.item_id
    AND ph.sale_price = excluded.sale_price
    AND upper(ph.valid_time) = lower(excluded.valid_time);

我期待该ON CONFLICT子句被执行,因为要插入一些具有相同的行item_idsale_price并且valid_time与现有行相邻。相反,我得到了这个:

ERROR:  there is no unique or exclusion constraint matching the ON CONFLICT specification

我误解了什么吗?我相信第二EXCLUDE个子句中的排除约束涉及相同的 3 列。我正在搜索文档,但ON CONFLICT说明对我来说不是那么清楚。

4

1 回答 1

7

该文档有些简洁的评论:

请注意,不支持排除约束作为带有ON CONFLICT DO UPDATE.

查看源代码使案例更加清晰:

  • 您永远不能将排除约束与ON CONFLICT DO UPDATE.

  • 但是,您可以使用

    ON CONFLICT ON CONSTRAINT price_history_item_id_valid_time_excl DO NOTHING
    

    也就是说,您可以将命名排除约束与DO NOTHING.

  • 排除约束没有“约束推断”,即,即使DO NOTHING您不能只在括号中指定索引表达式并让 PostgreSQL 找到相应的排除约束。

于 2019-04-16T20:01:49.777 回答