简体   繁体   English

根据三列和特定值创建mysql唯一键

[英]Create mysql unique key based on three columns and a specific value

I have a table with a unique index across two columns user_id and country_id 我有一个表,该表在两列user_idcountry_id上具有唯一索引

I have added a new column deleted_at so I can delete rows whilst keeping the data. 我添加了一个新列deleted_at以便可以在保留数据的同时删除行。

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. 我现在想更新唯一键,使其基于user_idcountry_id以及deleted_at 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. 使用以上内容作为参考,由于ID为2,因此无法添加行,但是,如果未设置第2行,则可以创建新行。

Modifying your table mytable should do the trick: 修改表mytable应该可以解决问题:

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. 根据CREATE INDEX语法,这仅适用于BDB存储。

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

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