postgresql - 在 Postgresql 中执行更新插入时,ON CONFLICT 子句中未使用部分索引

标签 postgresql indexing unique upsert partial-index

我有以下实体属性值表:

CREATE TABLE key_value_pair (
    id serial NOT NULL PRIMARY KEY,
    key varchar(255) NOT NULL,
    value varchar(255),
    is_active boolean
);

CREATE UNIQUE INDEX key_value_pair_key_if_is_active_true_unique ON key_value_pair (key) WHERE is_active = true;

此表中的示例条目是:

id |     key     | value | is_active 
----+-------------+-------+-----------
  1 | temperature | 2     | f
  2 | temperature | 12    | f
  3 | temperature | 15    | f
  4 | temperature | 19    | f
  5 | temperature | 23    | t
(5 rows)

因此,在任何时间点,对于任何给定的键,只应存在 1 个真正的 is_active 条目。

我正在该表上运行以下 upsert 语句:

INSERT INTO key_value_pair (key, value, is_active) VALUES ('temperature','20', true) 
ON CONFLICT (key, is_active)
DO UPDATE
SET value = '33', is_active = true;

但是,它失败了:

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

我想知道的是为什么它不使用唯一的部分索引 key_value_pair_key_if_is_active_true_unique

如果我放开“在任何时间点,对于任何给定的键,只有 1 个真正的 is_active 条目应该存在”子句并将索引更改为:

CREATE UNIQUE INDEX key_value_pair_key_if_is_active_true_unique ON key_value_pair (key, is_active);

我在 Postgres 网站上阅读了部分索引将由 ON CONFLICT 子句使用的文档。我想知道为什么在这种情况下不使用它。我在这里错过了什么,或者我犯了什么错误?

最佳答案

您必须使用索引谓词才能使用部分唯一索引。阅读 the documentation:

index_predicate

Used to allow inference of partial unique indexes. Any indexes that satisfy the predicate (which need not actually be partial indexes) can be inferred. Follows CREATE INDEX format.

在这种情况下:

INSERT INTO key_value_pair (key, value, is_active) VALUES ('temperature','20', false) 
ON CONFLICT (key) WHERE is_active
DO UPDATE
SET value = '33', is_active = true;

关于postgresql - 在 Postgresql 中执行更新插入时,ON CONFLICT 子句中未使用部分索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51551569/

相关文章:

sql - 如何合并和显示来自多个表的数据

Mysql 根据外键的存在改变表时间

postgresql - Postgres EXPLAIN 和放置索引的位置

ruby-on-rails - 为什么 "uniqueness: true"验证在我的测试 (Rails) 中不起作用?

java - 具有 PostgreSQL 初始序列池和更改的 JPA 2

postgresql - Go database/sql - 重新连接时发出命令

postgresql - 分区表上的 Postgres 错误(ERROR 42703 类型 X 的属性 4 已被删除)

indexing - hive中分区和索引的区别

MYSQL 选择排列;需要跨行的唯一值

arrays - 在数组中查找唯一整数