简体   繁体   中英

MySQL specific unique constraint only on specific values

I have a table with these fields:

id, field_a, field_b, status I have a unique constraint on (field_a, field_b, status)

I'm using the status (mapped as Integer) to manage also a soft delete so, when I need to mark an item as DELETD, I will update the status on the corresponding value.

In this way I will be able to create a new row with the same values for field_a, field_b values but with a different status. But in this logic there is a problem: I will have a constraint unique violation if I will deleted an item that was already deleted.

For example:

  1. INSERT ("Element A" "XXX") -> I will have: 1, Element A, XXX, 1 Status OK;
  2. DELETE 1 -> I will have: 1, Element A, XXX, 1 Status DELETED;
  3. INSERT ("Element A" "XXX") -> I will have: 2, Element A, XXX, 1 Status OK;
  4. DELETE ("Element A" "XXX") -> I will have an error because the unique constraint will be violated (Element A, XXX, 1 Status DELETED already exist);

Is it possible to have the same constraint but, regarding the status, I would like to use only a specific value (in this case only OK)?

When any component of unique index expression for a row is equal to NULL then this row is treated as unique anycase (because one NULL is not equal to another NULL). So:

Variant 1. Use NULL for status column value as a mark that the row is deleted.

fiddle for variant 1

Variant 2. Use an expression which converts DELETED status to NULL in the index expression (if your server version allows index by an expression):

CREATE UNIQUE INDEX idx
ON tablename (field_a, field_b, (CASE WHEN status = 'DELETED' THEN NULL ELSE status END))

fiddle for variant 2

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