How can I enforce that my composite key columns do not equal one another in MySQL?
-
06-03-2021 - |
質問
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.
所属していません dba.stackexchange