仅当其中一列为真时才向多列添加约束
Add constraint to multiple columns only if one of them is true
我有这个table
CREATE TABLE user (
user_id BIGINT NOT NULL,
modified_date DATE NOT NULL,
is_relevant BOOLEAN NOT NULL,
more columns...
);
我有 table 个用户,我保存了用户的历史记录。当更新用户数据时,我插入一个新行,修改日期,相同 user_id
,但 is_relevant
为真。 is_relevant
上只有最后更新的为真。因此,每次用户更新时,我都会将上一行更新为 false,并插入新行为 true。
我想为 user_id
和 is_relevant
上的唯一键添加约束,前提是 is_relevant
为真。我想避免两行具有相同用户 ID 的情况,并且在 is_relevant
.
中为真
有人知道怎么做吗?
您需要一个部分唯一索引,例如:
create unique index on "user" (user_id) where is_relevant;
阅读 the docs.
中的部分索引
我有这个table
CREATE TABLE user (
user_id BIGINT NOT NULL,
modified_date DATE NOT NULL,
is_relevant BOOLEAN NOT NULL,
more columns...
);
我有 table 个用户,我保存了用户的历史记录。当更新用户数据时,我插入一个新行,修改日期,相同 user_id
,但 is_relevant
为真。 is_relevant
上只有最后更新的为真。因此,每次用户更新时,我都会将上一行更新为 false,并插入新行为 true。
我想为 user_id
和 is_relevant
上的唯一键添加约束,前提是 is_relevant
为真。我想避免两行具有相同用户 ID 的情况,并且在 is_relevant
.
有人知道怎么做吗?
您需要一个部分唯一索引,例如:
create unique index on "user" (user_id) where is_relevant;
阅读 the docs.
中的部分索引