Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PostgreSQL中使用NOTNULL和unique约束更新列的特殊情况_Sql_Postgresql_Constraints_Unique Constraint - Fatal编程技术网

在PostgreSQL中使用NOTNULL和unique约束更新列的特殊情况

在PostgreSQL中使用NOTNULL和unique约束更新列的特殊情况,sql,postgresql,constraints,unique-constraint,Sql,Postgresql,Constraints,Unique Constraint,这是一个玩具示例,说明了PostgreSQL中的一个实际问题。下面的示例使用的是PostgreSQL 8.4.3服务器,但我怀疑其他版本也存在同样的问题 鉴于下表: => create table tmp_foo (foo boolean not null unique, bar boolean not null unique); => insert into tmp_foo (foo, bar) values (true, true), (false, false); => select *

这是一个玩具示例,说明了PostgreSQL中的一个实际问题。下面的示例使用的是PostgreSQL 8.4.3服务器,但我怀疑其他版本也存在同样的问题

鉴于下表:

=> create table tmp_foo (foo boolean not null unique, bar boolean not null unique); => insert into tmp_foo (foo, bar) values (true, true), (false, false); => select * from tmp_foo; foo | bar -----+----- t | t f | f 是否可以将该表修改为如下所示:

=> select * from tmp_foo; foo | bar -----+----- t | f f | t 不删除行或修改表架构?这:

=> update tmp_foo set bar = not bar; ERROR: duplicate key value violates unique constraint "tmp_foo_bar_key" 不起作用

如果允许删除,这将:

=> create temp table tmp_foo_2 as select * from tmp_foo; => update tmp_foo_2 set bar = not bar; => delete from tmp_foo; => insert into tmp_foo select * from tmp_foo_2;
工作。对于本例,这不是最简单的解决方案,但它很容易推广到更复杂的示例。

这样做需要可延迟的唯一约束

我们在每列中有尽可能多的行和唯一的值。因此,要对任何行进行变异,要么某些行必须临时违反唯一约束,要么必须删除某些行以避免违反约束。可延迟的唯一约束允许我们在事务中执行前一个临时冲突

如果你走了这么远,而且听起来是对的,那么你的问题的答案取决于博士后的版本

仅限8.4级的博士后。由此推论,唯一约束不能延迟

Postgres 9.0 Beta理论上提供了可延迟的唯一约束。我自己还没有尝试过,但是这个功能已经有很长一段时间了,所以我敢打赌当他们决定实现它时,他们是正确的


这里有两份关于9.0和的相关文档。正如您在后一个链接中所看到的,通过9.0文档中的SET constraints,唯一约束被明确列为支持延迟。我还没有探索这个新特性,我不能保证语义正是您所需要的。但这似乎正是问题所在。

这是一个有趣的问题,但我不明白您为什么不希望删除其中的内容。您已经创建了一组非常,呃,受约束的约束。你想解决的更大的问题是什么?