转自:https://blog.csdn.net/qq_35246620/article/details/72673014
唯一键与主键本质区别在于:唯一键允许字段值为空,并且允许多个空值存在。
唯一键
唯一键:每张表往往有多个字段需要具有唯一性,数据不能重复,但是在每张表中,只能有一个主键,因此唯一键就是用来解决表中多个字段需要具有唯一性的问题。
唯一键的本质与主键差不多,唯一键默认的允许字段为空,而且可以多个字段为空,因此空字段不参与唯一性的比较。
创建 unique key的两种方法
可以看到,当把非空的键设置为唯一键时,其性质就和主键一样了,会自动把他定义为主键
mysql> show create table my_unique1\G;
*************************** 1. row ***************************
Table: my_unique1
Create Table: CREATE TABLE `my_unique1` (
`number` char(10) NOT NULL COMMENT '学号',
`name` varchar(20) NOT NULL,
UNIQUE KEY `number` (`number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
唯一键可以为空值:
mysql> show create table my_unique\G;
*************************** 1. row ***************************
Table: my_unique
Create Table: CREATE TABLE `my_unique` (
`number` char(10) DEFAULT NULL COMMENT '学号',
`name` varchar(20) NOT NULL,
`gender` char(10) DEFAULT NULL,
UNIQUE KEY `number` (`number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
ERROR:
No query specified
mysql> insert into my_unique values(NULL,"mao","male");
Query OK, 1 row affected (0.06 sec)
mysql> select * from my_unique;
+--------+------+--------+
| number | name | gender |
+--------+------+--------+
| NULL | mao | male |
+--------+------+--------+
表的唯一键允许有多个
mysql> alter table my_unique add unique key(gender);
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> show create table my_unique\G;
*************************** 1. row ***************************
Table: my_unique
Create Table: CREATE TABLE `my_unique` (
`number` char(10) DEFAULT NULL COMMENT '学号',
`name` varchar(20) NOT NULL,
`gender` char(10) DEFAULT NULL,
UNIQUE KEY `number` (`number`),
UNIQUE KEY `gender` (`gender`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
唯一性:字段值不能重复!
mysql> select * from my_unique;
+--------+------+--------+
| number | name | gender |
+--------+------+--------+
| NULL | mao | male |
+--------+------+--------+
1 row in set (0.00 sec)
mysql> insert into my_unique values(NULL,"mao","male");
ERROR 1062 (23000): Duplicate entry 'male' for key 'gender'