Create mysql unique key based on three columns and a specific value
-
07-07-2021 - |
سؤال
I have a table with a unique index across two columns user_id
and country_id
I have added a new column deleted_at
so I can delete rows whilst keeping the data.
I would now like to update the unique key so that it is based on user_id
, country_id
and where deleted_at
IS NULL. Is this possible, if so how?
+----+---------+------------+------------+
+ id | user_id | country_id | deleted_at |
+----+---------+------------+------------+
+ 2 | 3 | 1 | NULL |
+ 3 | 3 | 1 | 2012-10-16 |
| 4 | 3 | 1 | 2012-10-15 |
+----+---------+------------+------------+
Using the above as reference, rows could not be added because of id 2, however if row 2 was not set a new row could be created.
المحلول
Modifying your table mytable should do the trick:
alter table mytable drop index user_country;
alter table mytable add
unique index user_country_deleted (user_id, country_id, deleted_at);
Edit: I was too quick. According to CREATE INDEX Syntax this works only for BDB storage.
لا تنتمي إلى StackOverflow