【发布时间】:2015-07-17 08:29:05
【问题描述】:
使用 MS SQL Server,以下工作正常:
CREATE TABLE #temptable(mykey int primary key)
INSERT INTO #temptable VALUES (1)
INSERT INTO #temptable VALUES (2)
UPDATE #temptable SET mykey=mykey+1
但是,使用 PostgreSQL,以下失败:
CREATE TABLE pg_temp.tbl_test(testkey integer primary key)
INSERT INTO pg_temp.tbl_test VALUES (1)
INSERT INTO pg_temp.tbl_test VALUES (2)
UPDATE pg_temp.tbl_test SET testkey=testkey+1
错误:重复键值违反唯一约束“tbl_test_pkey” 详细信息:密钥 (testkey)=(2) 已存在。
我需要增加一个表中一列的每个值,这是复合唯一约束的一部分。我怎样才能在一个语句中做到这一点?
谢谢!
编辑:如果您想知道为什么这是有道理的(至少对我而言),这里有一个更完整的场景。
我有一张按类别组织的项目表。每个项目在类别中都有特定的位置。
category_id (PK) | category_position (PK) | item_attribute_1 | item_attribute_2
1 | 1 | foo | bar
1 | 2 | foo2 | bar2
2 | 1 | foo4 | bar4
2 | 2 | foo3 | bar3
此表包含如下数据:
category1 : (foo, bar), (foo2, bar2)
category2 : (foo4, bar4), (foo3, bar3)
请注意, (foo4, bar4) 在 category2 中位于 (foo3, bar3) 之前。 现在,如果我想对一个类别中的项目重新排序,我需要更新 category_position...但是由于 PK,我不能像使用 SQL Server 那样使用 PostgreSQL 移动值。
【问题讨论】:
标签: sql postgresql sql-update unique-constraint