简体   繁体   English

将XOR模型检查成唯一约束

[英]Model XOR check into unique constraint

I am modeling a reactions table with columns user_id , post_id , reaction . 我正在用user_idpost_idreaction列对反应表进行建模。 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可以likedislikeviewed ,被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 . 现在的问题是,我也想为likedislike建模一个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 with UNIQUE to enforce uniqueness over a subset of a table. [...]另一个可能的应用是将WHEREUNIQUE结合使用以对表的子集实施唯一性。

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_NAMETABLE_NAME提供值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM