關系大致是這樣:
mysql中的unique約束是通過索引實現的;
key的含義是概念級別的,意味着唯一性,key的概念等價於unique;
所以說只要加了unique約束或者key,就會建立一個索引。
在mysql中,使用index或者unique(以及key)都會簡歷索引,區別在於是否允許重復,這個可以在show index命令中看到。
-
CREATE
TABLE user1(
-
id
INT PRIMARY
KEY AUTO_INCREMENT
COMMENT
'主鍵',
-
name
VARCHAR(
200)
COMMENT
'姓名',
-
age
int
COMMENT
'年齡',
-
unique aaa (
`name`,
`age`)
-
)
-
-
CREATE
TABLE user1(
-
id
INT PRIMARY
KEY AUTO_INCREMENT
COMMENT
'主鍵',
-
name
VARCHAR(
200)
COMMENT
'姓名',
-
age
int
COMMENT
'年齡',
-
constraint aaa
unique(
`name`,
`age`)
-
)
這兩種建表語句都會建立一個聯合索引:
mysql> show index from user1;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| user1 | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | | |
| user1 | 0 | aaa | 1 | name | A | 0 | NULL | NULL | YES | BTREE | | |
| user1 | 0 | aaa | 2 | age | A | 0 | NULL | NULL | YES | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
3 rows in set (0.00 sec)
都有一個index,第二列表明這個index是否允許重復。0代表不允許重復。
那么把這個aaa的unique刪掉,建立一個普通的index:
mysql> drop index aaa on user1;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> create index aaa on user1(`name`, `age`);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> show index from user1;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| user1 | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | | |
| user1 | 1 | aaa | 1 | name | A | 0 | NULL | NULL | YES | BTREE | | |
| user1 | 1 | aaa | 2 | age | A | 0 | NULL | NULL | YES | BTREE | | |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
3 rows in set (0.00 sec)
可以看到仍然有索引,但是第二列為1,表示該index可以允許重復。
原文地址:https://blog.csdn.net/u010900754/article/details/94314066