如果我在同一列上多次添加UNIQUE约束会发生什么?
当我们在同一列上多次添加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约束的次数上创建唯一的索引。
广告