mysql视频教程栏目今天着重介绍索引+explain,为需要面试的准备。
免费推荐:mysql视频教程
一、索引的介绍
- 在mysql中,索引就是数据结构,已经在文件中按照索引进行排序好的结构.
- 使用索引可以加快我们的查询速度,但是对我们的数据增删改效率会降低.
- 因为一个网站大部分都是查询,我们主要优化select语句.
二、MySQL中索引的分类
- 普通索引 key
- 唯一索引 unique key unique key 别名 别名可忽略 别名可忽略
- 主键索引 primary key(字段)
- 全文索引myisam引擎支持(只对英文进行索引,mysql版本5.6也支持),sphinx(中文搜索)
- 混合索引 多个字段组成的索引.如 key key_index(title,email)
三、索引的基本操作
1、给表添加索引
create table t_index( id int not null auto_increment, title varchar(30) not null default '', email varchar(30) not null default '', primary key(id), unique key uni_email(email) , key key_title(title) )engine=innodb charset=utf8;
查看表
desc tablename
mysql> desc t_index; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+------<em style="color:transparent">本文来源[email protected]搞@^&代*@码)网9</em>----------+ | id | int(11) | NO | PRI | NULL | auto_increment | | title | varchar(30) | NO | MUL | | | | email | varchar(30) | NO | UNI | | | +-------+-------------+------+-----+---------+----------------+ 3 rows in set (0.01 sec)
查看表的创建语句
show create table tbalename/G
mysql> show create table t_index/G; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/G' at line 1 mysql> show create table t_index\G; *************************** 1. row *************************** Table: t_index Create Table: CREATE TABLE `t_index` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(30) NOT NULL DEFAULT '', `email` varchar(30) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `uni_email` (`email`), KEY `key_title` (`title`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 1 row in set (0.00 sec) ERROR: No query specified
2、删除索引
-
删除主键索引
alter table table_name drop primary key;
注意:
mysql> alter table t_index drop primary key; ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key
主键不一定是自增长,但是自增长一定是主键。
删除逐渐之前先要把主键索引的自增长去掉。
mysql> alter table t_index modify id int not null; Query OK, 0 rows affected (0.05 sec) Records: 0 Duplicates: 0 Warnings: 0
再来删除主键
mysql> alter table t_index drop primary key; Query OK, 0 rows affected (0.04 sec) Records: 0 Duplicates: 0 Warnings: 0
-
删除普通和唯一的索引
alter table table_name drop key ‘索引的别名’
实际操作
mysql> alter table t_index drop key uni_email; Query OK, 0 rows affected (0.03 sec) Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table t_index drop key key_title; Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0
3、添加索引
alter table t_index add key key_title(title); alter table t_index add key uni_email(email); alter table t_index add primary key(id);
4、有无索引对比
create table article( id int not null auto_increment, no_index int, title varchar(30) not null default '', add_time datetime, primary key(id) );