我有一个表,其中有一列包含“有效期至”日期,我想确保只能在表中的一行中将其设置为空。有没有简单的方法可以做到这一点?
我的表看起来像这样(postgres):
CREATE TABLE 123.myTable(
some_id integer NOT NULL,
valid_from timestamp without time zone NOT NULL DEFAULT now(),
valid_until timestamp without time zone,
someString character varying)
some_id
和 valid_from
是我的 PK。如果此 PK 已存在空值行,我不希望任何人在 valid_until 列中输入空值行。
谢谢
最佳答案
在 PostgreSQL 中,您有两种基本方法。
- 使用
'infinity'
而不是 null。然后你的唯一约束按预期工作。或者,如果您不能这样做: 在 mytable(someid) 上创建唯一索引 null_valid_from,其中 valid_until 为 NULL
这两种方法我都用过。我发现通常第一种方法更简洁,它允许您在较新版本的 PostgreSQL 中更好地使用范围类型和排除约束(以确保没有两个时间范围基于给定的给定 someid 重叠),但是第二种方法通常很有用首先无法完成。
关于sql - 间隔 : How can I make sure there is just one row with a null value in a timstamp column in table?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5965696/