MySQL索引
1.建表
首先先建立一张测试表,使用Innodb引擎
mysql> create table test_index( -> id int, -> name varchar(20) -> ) engine innodb default charset utf8 -> ;
查看表上的索引,使用如下语句
mysql> show index from test_index;
返回Empty Set。
2.alter方式建立索引
为test_index表添加一个主键
alter table test_index add primary key(id)
这个时候在用 show index from test_index查看索引的话,会发现多了一条索引记录,这是因为mysql会自动为主键字段建立索引。
我们下面看下索引的的其他的用法,由于上面建立的表字段太少,我们给test_index表另外添加两个字段
alter table test_index add column age int; alter table test_index add column city varchar(20);
用下面语句给name字段添加索引
alter table test_index add index idx_name_field(name);
用下面语句给city字段添加唯一索引
alter table test_index add unique(city);
3.create语法建立索引
上面演示的都是通过alter来添加索引,还可以通过create来添加索引,在新建两个字段用以演示
mysql> alter table test_index add column hello varchar(20); Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table test_index add column world varchar(20); Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0
用如下语句建立普通索引:
mysql> create index idx_hello on test_index(hello); Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0
使用如下语句建立唯一索引:
mysql> create unique index idx_world on test_index(world); Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0
使用create语法不支持建立primary key索引
4.使用alter语法删除索引
mysql> alter table test_index drop index idx_hello; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table test_index drop primary key; Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0
5.使用drop语法删除索引
mysql> drop index idx_world on test_index; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0
6.结尾
接下来查看数据库中具有的索引,以便全部删除:
mysql> show keys from test_index; +------------+------------+----------------+--------------+-------------+-----------+-------------+- ---------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +------------+------------+----------------+--------------+-------------+-----------+-------------+- ---------+--------+------+------------+---------+---------------+ | test_index | 0 | city | 1 | city | A | 0 | NULL | NULL | YES | BTREE | | | | test_index | 1 | idx_name_field | 1 | name | A | 0 | NULL | NULL | YES | BTREE | | | +------------+------------+----------------+--------------+-------------+-----------+-------------+- ---------+--------+------+------------+---------+---------------+ 2 rows in set (0.00 sec)
mysql> drop index city on test_index; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> drop index idx_name_field on test_index; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> show index from test_index; Empty set (0.00 sec)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。