简体   繁体   中英

How to make two column unique in mysql with value 0/1 in one table?

I have a table with these two column, I want to make uniqueness only if columng is_deleted value is 0 for email column, so below rows are valid if abc@gmail.com with 1 enters it will allow where if abc@gmail.com with 0 enters it should not allow. How to make this constraint in mysql?

email           is_deleted
abc@gmail.com   1
abc@gmail.com   1
abc@gmail.com   1
abc@gmail.com   0

I tried to make unique both column, It allows for one entry but it fails after this.

abc@gmail.com   1
abc@gmail.com   0

I am working on soft deletion with unique fields.

Thanks for your help.

This is actually one of the better questions I've seen on Stack Overflow in a while. From my understanding, this is not possible per se, at least without doing something a bit creative.

The only way I can imagine making it work is to create an extra field which can contain an arbitrary random IFF is_deleted == 1, and to use a unique key against all 3.

As such, the table might look something like this:

email           is_deleted  null_ident
abc@gmail.com   1           0cc175b9c0f1b6a831c399e269772661
abc@gmail.com   1           92eb5ffee6ae2fec3ad71c777531578f
abc@gmail.com   1           4a8a08f09d37b73795649038408b5f33
abc@gmail.com   0           0

So, a unique key against all 3 of these would only lock when is_deleted is 0 and null_ident is also 0 (as handled via business logic). If you need to set is_deleted against the address, you'd also set an ident key as well.


Also, an addition... in the example above, null_ident is just an md5 hash for generally acceptable uniqueness. Depending on what you need, you may want a stronger (or, more likely, a less strong) hash. Heck, a timestamp would probably suit your needs fine. And a char(36) in the index is a bit heavy... but so is a varchar(310) for the email address. : )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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