[英]Model XOR check into unique constraint
I am modeling a reactions table with columns user_id
, post_id
, reaction
. 我正在用
user_id
, post_id
和reaction
列对反应表进行建模。 I want to have entries in this row to be unique which can be easily achieved with a unique index. 我希望此行中的条目是唯一的,这可以通过唯一索引轻松实现。
reactions
can be like
, dislike
, viewed
, applauded
reactions
可以like
, dislike
, viewed
,被applauded
Now the problem is, I also want to model a XOR relationship for like
and dislike
, meaning, when there is already a row with like
for a given pst and user, it shoudn't be possible to add another row with dislike
. 现在的问题是,我也想为
like
和dislike
建模一个XOR关系,这意味着,对于给定的pst和user已经存在具有like
的行时,应该不可能再添加另一条具有dislike
行。
Since there are other optional reactions I don't know to write the constraint check for this. 由于还有其他可选反应,因此我不知道为此编写约束检查。 Is this even possible?
这有可能吗?
You only want the (user_id, post_id)
uniqueness to apply when the reaction
is 'like'
or 'dislike'
. 您只希望
(user_id, post_id)
唯一性在reaction
为'like'
或'dislike'
。 That's a partial index : 那是一个局部索引 :
When the
WHERE
clause is present, a partial index is created.存在
WHERE
子句时,将创建部分索引 。 A partial index is an index that contains entries for only a portion of a table, usually a portion that is more useful for indexing than the rest of the table.部分索引是仅包含表一部分的条目的索引,通常一部分索引比表的其余部分更有用。 [...] Another possible application is to use
WHERE
withUNIQUE
to enforce uniqueness over a subset of a table.[...]另一个可能的应用是将
WHERE
与UNIQUE
结合使用以对表的子集实施唯一性。
You want an index like this: 您想要这样的索引:
create unique index INDEX_NAME
on TABLE_NAME (user_id, post_id)
where reaction in ('like', 'dislike')
where you'd supply values for INDEX_NAME
and TABLE_NAME
of course. 您将在哪里为
INDEX_NAME
和TABLE_NAME
提供值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.