MYSQL入门学习之九:索引的基本操作
一、创建索引
MYSQL常用的索引类型主要有以下几种:
1、普通索引
CREATE INDEX idx_name ON table_name(table_col(length));
如果索引字段是CHAR,varchar类型,length可以指定小于字段实际长度;如果是BLOB和TEXT类型,必须指定length。
mysql> create index idx_name on user(name(10));
mysql> show index from user;
+-------+------------+----------+--------------+-------------+-----------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation |
+-------+------------+----------+--------------+-------------+-----------+
| user | 1 | idx_name | 1 | name | A |
+-------+------------+----------+--------------+-------------+-----------+
2、唯一索引
CREATE UNIQUE INDEX idx_name ON table_name(table_col(length));
它与普通索引类似,但不同的是,其索引列的值必须唯一,但允许有空值。
mysql> create unique index idx_cn_name_u on user(cn_name(20));
mysql> show index from user;
+-------+------------+---------------+--------------+-------------+-----------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation |
+-------+------------+---------------+--------------+-------------+-----------+
| user | 0 | idx_cn_name_u | 1 | cn_name | A |
| user | 1 | idx_name | 1 | name | A |
+-------+------------+---------------+--------------+-------------+-----------+
3、主键索引
ALTER TABLE table_name ADD PRIMARY KEY (table_col);
它是一种特殊的唯一索引,且不允许有空值。一个表只能有一个主键索引。
mysql> alter table user add primary key (id);
mysql> show index from user;
+-------+------------+---------------+--------------+-------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name |
+-------+------------+---------------+--------------+-------------+
| user | 0 | PRIMARY | 1 | id |
| user | 0 | idx_cn_name_u | 1 | cn_name |
| user | 1 | idx_name | 1 | name |
+-------+------------+---------------+--------------+-------------+
4、组合索引
CREATE INDEX idx_name ON table_name(table_col_1,table_col_2,...,table_col_n);
它允