简体   繁体   English

具有条件的MySQL唯一索引

[英]MySQL Unique Index with condition

I need to have a uniqueness check either with an Index or Constraint on a table, but this only has to happen if the value of a boolean field is true. 我需要在表上使用Index或Constraint进行唯一性检查,但只有在布尔字段的值为true时才会发生这种情况。 If it's false, then it's fine for there to be a duplicate row. 如果它是假的,那么可以有一个重复的行。 I don't think this is possible with a constraint or index in mysql, so is there any other possible solution for going about this problem? 我不认为这可以用mysql中的约束或索引,所以有没有其他可能的解决方案来解决这个问题?

If you can slightly change the definition of the field to be "1" for "true" and "NULL" for false, then you can use a unique index on the two columns: 如果您可以将字段的定义稍微更改为“1”表示“true”而“NULL”表示false,则可以在两列上使用唯一索引:

create unique index idx_table_col1_col2 on table(col1, col2)

NULL values can be duplicated in a unique index. 可以在唯一索引中复制NULL值。

Alternatively, you would have to use a trigger to enforce this condition. 或者,您必须使用触发器来强制执行此条件。

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

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