当我们多次在同一列上添加 UNIQUE 约束时,MySQL 将在该列上为我们添加 UNIQUE 约束的次数创建索引。
示例
假设我们有表“employee”,其中“empid”列有 UNIQUE 约束。可以通过以下查询进行检查 -
mysql> Describe employee;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| empid | int(11) | YES | UNI | NULL | |
| first_name | varchar(20) | YES | | NULL | |
| last_name | varchar(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
3 rows in set (0.12 sec)
现在,当我们运行查询 SHOW INDEX 时,它会给出索引的名称,只有一个索引,在“empid”列上创建。
mysql> Show index from employee\G;
*************************** 1. row ***************************
Table: employee
Non_unique: 0
Key_name: empid
Seq_in_index: 1
Column_name: empid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
1 row in set (0.00 sec)
在以下查询的帮助下,我们在同一列“empid”上添加了另一个 UNIQUE 约束 -
mysql> Alter table employee ADD UNIQUE(empid);
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
现在,当我们运行查询 SHOW INDEX 时,它会给出索引的名称,即在“empid”列上创建的两个索引“empid”和“empid_2”。
mysql> Show index from employee12\G;
*************************** 1. row ***************************
Table: employee
Non_unique: 0
Key_name: empid
Seq_in_index: 1
Column_name: empid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
*************************** 2. row ***************************
Table: employee
Non_unique: 0
Key_name: empid_2
Seq_in_index: 1
Column_name: empid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
2 rows in set (0.00 sec)
在以下查询的帮助下,我们在同一列“empid”上添加了另一个 UNIQUE 约束 -
mysql> Alter table employee ADD UNIQUE(empid);
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
现在,当我们运行查询 SHOW INDEX 时,它会给出索引的名称,在列“empid”上创建的三个索引“empid”和“empid_2”、“empid_3”。
mysql> Alter table employee ADD UNIQUE(empid);
Query OK, 0 rows affected (0.30 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> Show index from employee\G;
*************************** 1. row ***************************
Table: employee
Non_unique: 0
Key_name: empid
Seq_in_index: 1
Column_name: empid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
*************************** 2. row ***************************
Table: employee
Non_unique: 0
Key_name: empid_2
Seq_in_index: 1
Column_name: empid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
*************************** 3. row ***************************
Table: employee
Non_unique: 0
Key_name: empid_3
Seq_in_index: 1
Column_name: empid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
3 rows in set (0.00 sec)
从这个意义上说,我们可以说,MySQL 将在我们在该列上添加 UNIQUE 约束的次数的列上创建唯一索引。