MySQL实现条件唯一性

Posted wzy0623

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL实现条件唯一性相关的知识,希望对你有一定的参考价值。

在Oracle中可以使用函数索引来实现,例如:

create unique index xpto_table_idx1 on xpto_table(case when status_x <>5 then obj_x else null end);

当status_x<>5时,obj_x的值唯一,否则可以重复。在mysql中不支持这样的功能,但可以通过虚拟列来实现。看下面一个简单例子。

需求:表t1有a、b、c三列,a为主键,仅当t1.b=1时,t1.c的值唯一。

实现:

-- 创建示例表并添加数据
create table t1 (a int primary key, b int, c int);
insert into t1 values (1,1,10),(2,2,20),(3,3,30);

-- 创建虚拟列
alter table t1 add flag int generated always as (if(b =1,  b, null)) virtual;
-- 创建唯一约束
alter table t1 add constraint unique (flag);

测试:

mysql> insert into t1 (a,b,c) values (5,2,200),(6,3,300);
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> insert into t1 (a,b,c) values (4,1,100);
ERROR 1062 (23000): Duplicate entry '1' for key 'flag'
mysql> select * from t1;
+---+------+------+------+
| a | b    | c    | flag |
+---+------+------+------+
| 1 |    1 |   10 |    1 |
| 2 |    2 |   20 | NULL |
| 3 |    3 |   30 | NULL |
| 5 |    2 |  200 | NULL |
| 6 |    3 |  300 | NULL |
+---+------+------+------+
5 rows in set (0.00 sec)

该方法在MySQL 5.7及以上版本中通用。

以上是关于MySQL实现条件唯一性的主要内容,如果未能解决你的问题,请参考以下文章

MySQL INSERT插入条件判断:如果不存在则插入

MySQL 索引

MySQL 索引

如果条件唯一,则 MySQL 不同计数

创建包含具有条件的唯一行的新表; MySQL

如果条件唯一,MySQL独特计数