我有一个 PostgreSQL 表,在不同字段上有两个唯一索引(nickname
和 email
)。我正在尝试插入一条违反这两个约束的记录。我希望首先检查并报告昵称
。
我观察到首先检查首先创建的索引,因此我首先在 nickname
上创建索引,它确实有效。但这种行为是指定的吗?我可以依赖它,还是只是偶然?
最佳答案
PostgreSQL 使用RelationGetIndexList
获取索引列表,评论说:
/*
* RelationGetIndexList -- get a list of OIDs of indexes on this relation
[...]
*
* The returned list is guaranteed to be sorted in order by OID. This is
* needed by the executor, since for index types that we obtain exclusive
* locks on when updating the index, all backends must lock the indexes in
* the same order or we will get deadlocks (see ExecOpenIndices()). Any
* consistent ordering would do, but ordering by OID is easy.
[...]
*/
OID(对象标识符)是向上计数的 4 字节无符号整数,因此通常较晚的对象将获得更高的 OID。这与您观察到的情况相符。
但是,一旦 OID 范围用完,它们就会绕回并从 FirstNormalObjectId
(16384) 重新开始,因此不能保证首先创建的索引具有较低的 OID。
您可以使用如下查询:
SELECT 'indexname'::regclass::oid;
查找每个索引的 OID。
要获取表上所有索引的 OID,请使用
SELECT indexrelid AS oid, indexrelid::regclass
FROM pg_index
WHERE indrelid = 'tablename'::regclass;
关于postgresql - 插入记录违反了 PostgreSQL 中的两个唯一索引。首先检查哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55104384/