描述
该语句用来创建索引。索引是创建在表上的,对数据库表中一列或多列的值进行排序的一种结构。其作用主要在于提高查询的速度,降低数据库系统的性能开销。
语法
CREATE [UNIQUE] INDEX index_name
ON table_name (index_col_name,...)
[index_type] [index_options]
index_type:
USING BTREE
index_options:
index_option [index_option...]
index_option:
GLOBAL | LOCAL
| COMMENT 'string'
| COMPRESSION [=] {NONE | LZ4_1.0 | LZO_1.0 | SNAPPY_1.0 | ZLIB_1.0}
| BLOCK_SIZE [=] size
| STORING(column_name_list)
| VISIBLE | INVISIBLE
index_col_name:
column_name [(length)] [ASC | DESC]
column_name_list:
column_name [, column_name...]
参数解释
| 参数 | 描述 |
|---|---|
| index_name | 指定要创建的索引名称。 |
| table_name | 指定索引所属的表名。 |
| index_col_name | 指定索引的列名,每个列名后都支持 ASC(升序),不支持 DESC(降序)。默认为升序。 建立索引的排序方式为:首先以 index_col_name 中第一个列的值排序;该列值相同的记录,按下一列名的值排序;以此类推。 |
| column_name | 用于创建索引的列名。 |
| length | 对于字符串列,可以使用 col_name(length) 语法截取字符串的部分用于创建索引。 支持的数据类型有 CHAR、VARCHAR、BINARY 与 VARBINARY。 |
| index_type | 索引类型,只支持 USING BTREE,表示使用 B-Tree 索引。 |
| UNIQUE | 指定为唯一索引。 |
| index_option | 指定索引选项,多个 index_option 以空格分隔。 |
| GLOBAL | LOCAL | 指定该索引是全局索引或局部索引,默认是 LOCAL。 |
| COMMENT | 指定注释。 |
| COMPRESSION | 指定压缩算法。 |
| BLOCK_SIZE | 指定微块大小。 |
| STORING | 表示索引表中冗余存储某些列,以提高系统查询性能。 |
示例
执行以下命令,创建表
test。obclient> CREATE TABLE test (c1 int primary key, c2 VARCHAR(10));执行以下命令,创建表
test在c1、c2列上的索引test_index。obclient> CREATE INDEX test_index ON test (c1, c2 ASC);执行以下命令,查看表
test的索引。可见具有两行
Key_name为test_index的记录,分别使用c1、c2作为索引列,并且使用c2的列作为test_index的Sub_part。obclient> SHOW INDEX FROM test; +-------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | +-------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+ | test | 0 | PRIMARY | 1 | c1 | A | NULL | NULL | NULL | | BTREE | available | | YES | | test | 1 | test_index | 1 | c1 | A | NULL | NULL | NULL | | BTREE | available | | YES | | test | 1 | test_index | 2 | c2 | A | NULL | NULL | NULL | YES | BTREE | available | | YES | +-------+------------+------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----------+---------------+---------+ 3 rows in set