我已经定义了这个表:
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_id
,sale_price
并且valid_time
与现有行相邻。相反,我得到了这个:
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
我误解了什么吗?我相信第二EXCLUDE
个子句中的排除约束涉及相同的 3 列。我正在搜索文档,但ON CONFLICT
说明对我来说不是那么清楚。