MySQL 如何创建多列唯一索引?
要创建多列唯一索引,我们需要在多个列上指定索引名称。以下示例将在“employee”表的“empid”、“first_name”和“last_name”列上创建名为“id_fname_lname”的多列索引 −
mysql> Create UNIQUE INDEX id_fname_lname on employee(empid,first_name,last_name);
Query OK, 0 rows affected (0.41 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> describe 员工;
+------------+-------------+------+-----+---------+-------+
|字段 |类型 | Null | Key | 默认 |额外 |
+------------+-------------+------+-----+---------+-------+
| empid | int(11)|是 | MUL | NULL | |
| first_name | varchar(20)|是 | | NULL | |
| last_name | varchar(20)|是 | | NULL | |
+------------+-------------+------+-----+---------+-------+
3行在集合(0.12 sec)中
从上面的查询结果集中,我们可以看到一个表中定义了多个索引。如果忘记了索引的详细信息,我们可以运行以下查询 −
mysql> Show index from employee\G
*************************** 1. row ***************************
表:employee
Non_unique: 0
Key_name: id_fname_lname
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 ***************************
表:employee
Non_unique: 0
Key_name: id_fname_lname
Seq_in_index: 2
Column_name: first_name
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
*************************** 3. row ***************************
表:employee
Non_unique: 0
Key_name: id_fname_lname
Seq_in_index: 3
Column_name: last_name
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
3行在集合(0.00 sec)中
我们可以从上面的结果集中观察到,“key_name”字段中的值相同,因为我们已经在表的所有列上创建了多列索引。
阅读更多:MySQL 教程