在我的数据库中,我的记录如下:
Start_date | Product_code
2009-01-01 | 1
2010-01-01 | 1
...
...
我想将 start_date 更新为 start_date + 1。
但是我有 (Start_date, product_code) 作为我的主键。
如果我以
update products set start_date = start_date + '1 year'::interval ;
这会返回一个错误,指出另一个条目已经存在(因为 2010-01-01,1 已经是表中的一个条目)。
基本上,我需要在按开始日期降序排列条目后进行更新。
我可以创建另一个具有相同架构的表,以排序方式将所有条目复制到临时表,截断原始表,然后在添加开始日期后填充该表中的条目。
还有其他有效的方法吗?
最佳答案
从 Postgres 9.0 开始,您可以将主键定义为可延迟的。这意味着它只会在您提交事务时进行检查,而不是针对每一行进行检查。
create table products
(
start_date date not null,
product_code integer not null,
primary key (start_date, product_code) deferrable
);
insert into products
values
(date '2009-01-01', 1),
(date '2010-01-01', 1),
(date '2011-01-01', 1),
(date '2012-01-01', 1);
update products
set start_date = start_date + interval '1' year;
SQLFiddle:http://sqlfiddle.com/#!12/19b56/1
关于Postgresql - 排序后更新表的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18914868/