postgresql - 如何在覆盖“CREATE UNIQUE INDEX”约束时批量更新?
问题描述
我有桌子
CREATE TABLE my_table (
ranking INTEGER NOT NULL,
name TEXT NOT NULL,
is_deleted BOOLEAN NOT NULL
);
CREATE UNIQUE INDEX exists_const ON my_table ranking WHERE (is_deleted = FALSE);
| ranking | name | is_deleted |
| 1 | A | true |
| 2 | B | true |
| 1 | C | true |
| 1 | D | false |
| 2 | E | false |
| 3 | F | false |
所以当我想更新 D、E、F 的新排名时
UPDATE "my-table" AS t SET "ranking"=v."ranking" FROM
(VALUES(1, 'F', 'false'),(2, 'D', 'false'), (3, 'E', 'false'))
AS v("ranking","name", 'is_deleted') WHERE v.name = t.name
| 1 | F | false |
| 2 | D | false |
| 3 | E | false |
我有duplicate key value violates unique constraint "exists_const"
错误。即使新行根本没有重复项。如何执行此类更新?
解决方案
The problem can be solved by Deferring the check at the end of the transaction, but you cannot do it with INDEX (as far as I know). The workaround I can give is to use EXCLUDE as described below:
CREATE TABLE my_table (
ranking INTEGER NOT NULL,
name TEXT NOT NULL,
is_deleted BOOLEAN NOT NULL,
EXCLUDE USING BTREE (ranking WITH =) WHERE (not is_deleted) DEFERRABLE
);
Attention to the 'DEFERRABLE'
Here to populate initial data:
insert into my_table ( ranking, name, is_deleted)
values
(1, 'A', true),
(2, 'B', true),
(1, 'C', true),
(1, 'D', false),
(2, 'E', false),
(3, 'F', false);
Now if you execute :
UPDATE "my_table" AS t
SET "ranking" = v."ranking"
FROM
(VALUES(1, 'F', 'false'),(2, 'D', 'false'), (3, 'E', 'false'))
AS v("ranking","name", "is_deleted")
WHERE v.name = t.name;
It should work.
And to test the uniqueness I tested it with :
insert into my_table ( ranking, name, is_deleted)
values
(3, 'G', false);
推荐阅读
- javascript - 此过滤器未返回预期结果
- javascript - Angular Lazy Loading:Lighthouse 在应该尚未加载的脚本上报告“删除未使用的 JavaScript”
- performance - 具有周期性边界条件的 Fortran 2D 网格 - 高效实施
- reactjs - 奇怪的“函数作为 React 孩子无效”
- javascript - 函数不返回星期几
- list - Haskell - 使用 foldl 或 foldr 而不是模式匹配在给定索引处使用新值更新列表
- iframe - 嵌入式 Cvent 页面上的 iframe 错误。在 Firefox 上工作,但没有别的
- python - 如何使用 PySide 在字符顶部显示拼音?
- algorithm - 是否可以使用 Nelder-Mead 优化算法来解决旅行商问题?
- pyspark - 当pyspark 2.2.0中缺少日期时如何计算一系列日期的标准偏差