I have a pivot table in which there is a composite key made up of two columns that reference the same table. The columns are requester_id and addressee_id and both of them refer to the id field on a users table. I'm trying to make sure that something like this cannot happen:

requester_id   addressee_id   created_at
1              1              2020-08-09 18:40:23

I've also added an index expression to ensure that there can only be one unique pairing of IDs as well:

alter table `user_relationships` 
add unique index `unique_relationships_index`
((least(requester_id,addressee_id)), (greatest(requester_id,addressee_id)))

To avoid having 1|2 and 2|1.

有帮助吗?

解决方案

MySQL-8.0.16 enforces check constraints

alter table user_relationships add check (requester_id <> addressee_id)

Afterwards:

insert into user_relationships values (3,3,NOW())
Check constraint 'user_relationships_chk_1' is violated.

ref: fiddle

许可以下: CC-BY-SA归因
不隶属于 dba.stackexchange
scroll top