使用MS SQL Server,以下内容可以正常工作:
然而,使用PostgreSQL时,以下操作会失败:
这张表格包含以下数据:
请注意,在category2中,(foo4, bar4)在(foo3, bar3)之前。 现在,如果我想重新排列一个类别中的项目,我需要更新category_position...但由于主键的存在,我不能像使用SQL Server那样使用PostgreSQL来移动值。
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)
请注意,在category2中,(foo4, bar4)在(foo3, bar3)之前。 现在,如果我想重新排列一个类别中的项目,我需要更新category_position...但由于主键的存在,我不能像使用SQL Server那样使用PostgreSQL来移动值。