快来一起看方便快捷的索引

一、索引概述

1. 索引的概念

  • 索引是一个排序的列表,在这个列表中存储着索引的值和包含这个值的数据所在行的物理地址(类似于 C 语言的链表通过指针指向数据记录的内存地址)。
  • 使用索引后可以不用扫描全表来定位某行的数据,而是先通过索引表找到该行数据对应的物理地址然后访问相应的数据,因此能加快数据库的查询速度。
  • 索引就好比是一本书的目录,可以根据目录中的页码快速找到所需的内容。
  • 索引是表中一列或者若干列值排序的方法。
  • 建立索引的目的是加快对表中记录的查找或排序。

2. 索引的作用

  • 设置了合适的索引之后,数据库利用各种快速定位技术,能够大大加快查询速度,这是创建索引的最主要的原因。
  • 当表很大或查询涉及到多个表时,使用索引可以成千上万倍地提高查询速度。
  • 可以降低数据库的 IO 成本,并且索引还可以降低数据库的排序成本。
  • 通过创建唯一(键)性索引,可以保证数据表中每一行数据的唯一性。
  • 可以加快表与表之间的连接。
  • 在使用分组和排序时,可大大减少分组和排序的时间。

PS:索引的副作用
索引需要占用额外的磁盘空间;
对于 MyISAM 引擎而言,索引文件和数据文件是分离的,索引文件用于保存数据记录的地址。而 InnoDB 引擎的表数据文件本身就是索引文件;
在插入和修改数据时要花费更多的时间,因为索引也要随之变动。

3. 创建索引的原则依据

索引虽可以提升数据库查询的速度,但并不是任何情况下都适合创建索引。因为索引本身会消耗系统资源,在有索引的情况下,数据库会先进行索引查询,然后定位到具体的数据行,如果索引使用不当,反而会增加数据库的负担。

创建索引需要遵循下列原则

  • 表的主键、外键必须有索引。因为主键具有唯一性,外键关联的是子表的主键,查询时可以快速定位
  • 记录数超过 300 行的表应该有索引。如果没有索引,需要把表遍历一遍,会严重影响数据库的性能
  • 经常与其他表进行连接的表,在连接字段上应该建立索引
  • 唯一性太差的字段不适合建立索引
  • 更新太频繁地字段不适合创建索引
  • 经常出现在 where 子句中的字段,特别是大表的字段,应该建立索引
  • 索引应该建在选择性高的字段上
  • 索引应该建在小字段上,对于大的文本字段甚至超长字段,不要建索引

二、索引的分类和创建

1. 创建模板

mysql -u root -p

create database info;
use info;
create table member (id int(10),name varchar(10),cardid varchar(18),phone varchar(11),address varchar(50),remark text);
desc member;

insert into member values (1,'zhangsan','123','111111','nanjing','this is vip');
insert into member values (2,'wangwu','12345','222222','benjing','this is normal');
insert into member values (3,'qianqi','1234567','333333','shanghai','this is vip');
insert into member values (4,'lisi','1234','444444','nanjing','this is normal');
insert into member values (5,'zhaoliu','123456','555555','nanjing','this is vip');

select * from member;
1234567891011121314

示例:

MySQL root@localhost:(none)> create database info;
Query OK, 1 row affected
Time: 0.001s
MySQL root@localhost:(none)> use info;
You are now connected to database "info" as user "root"
Time: 0.000s
MySQL root@localhost:info> create table member (id int(10),name varchar(10),cardid varchar(18),phone varchar(11),address varchar(50),remark text);
Query OK, 0 rows affected
Time: 0.010s
MySQL root@localhost:info> desc member;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id      | int(10)     | YES  |     | <null>  |       |
| name    | varchar(10) | YES  |     | <null>  |       |
| cardid  | varchar(18) | YES  |     | <null>  |       |
| phone   | varchar(11) | YES  |     | <null>  |       |
| address | varchar(50) | YES  |     | <null>  |       |
| remark  | text        | YES  |     | <null>  |       |
+---------+-------------+------+-----+---------+-------+
6 rows in set
Time: 0.008s
MySQL root@localhost:info> insert into member values (1,'zhangsan','123','111111','nanjing','this is vip');
Query OK, 1 row affected
Time: 0.003s
MySQL root@localhost:info> insert into member values (2,'wangwu','12345','222222','benjing','this is normal');
Query OK, 1 row affected
Time: 0.003s
MySQL root@localhost:info> insert into member values (3,'qianqi','1234567','333333','shanghai','this is vip');
Query OK, 1 row affected
Time: 0.004s
MySQL root@localhost:info> insert into member values (4,'lisi','1234','444444','nanjing','this is normal');
Query OK, 1 row affected
Time: 0.003s
MySQL root@localhost:info> insert into member values (5,'zhaoliu','123456','555555','nanjing','this is vip');
Query OK, 1 row affected
Time: 0.004s
MySQL root@localhost:info> select * from member;
+----+----------+---------+--------+----------+----------------+
| id | name     | cardid  | phone  | address  | remark         |
+----+----------+---------+--------+----------+----------------+
| 1  | zhangsan | 123     | 111111 | nanjing  | this is vip    |
| 2  | wangwu   | 12345   | 222222 | benjing  | this is normal |
| 3  | qianqi   | 1234567 | 333333 | shanghai | this is vip    |
| 4  | lisi     | 1234    | 444444 | nanjing  | this is normal |
| 5  | zhaoliu  | 123456  | 555555 | nanjing  | this is vip    |
+----+----------+---------+--------+----------+----------------+
5 rows in set
Time: 0.006s
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849

2. 普通索引

普通索引是最基本的索引类型,没有唯一性之类的限制。

(1) 直接创建索引

CREATE INDEX 索引名 ON 表名 (列名[(length)]);
#(列名[(length)]):length 是可选项,如果忽略 length 的值,则使用整个列的值作为索引。
#如果指定使用列前的 length 个字符来创建索引,这样有利于减小索引文件的大小。
#索引名建议以 "_index" 结尾。
_______________________________________________
create index phone_index on member (phone);
select phone from member;
show create table member;
12345678

示例:

MySQL root@localhost:info> create index phone_index on member (phone);
Query OK, 0 rows affected
Time: 0.030s
MySQL root@localhost:info> select phone from member;
+--------+
| phone  |
+--------+
| 111111 |
| 222222 |
| 333333 |
| 444444 |
| 555555 |
+--------+
5 rows in set
Time: 0.005s
MySQL root@localhost:info> show create table member\G;
***************************[ 1. row ]***************************
Table        | member
Create Table | CREATE TABLE "member" (
  "id" int(10) DEFAULT NULL,
  "name" varchar(10) DEFAULT NULL,
  "cardid" varchar(18) DEFAULT NULL,
  "phone" varchar(11) DEFAULT NULL,
  "address" varchar(50) DEFAULT NULL,
  "remark" text,
  KEY "phone_index" ("phone")
) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set
Time: 0.001s
123456789101112131415161718192021222324252627282930

(2) 修改表方式创建

ALTER TABLE 表名 ADD INDEX 索引名 (列名);
——————————————————————————————————————————————————
alter table member add index id_index(id);
select id from member;
select id,name from member;
12345

示例:

MySQL root@localhost:info> alter table member add index id_index(id);
You're about to run a destructive command.
Do you want to proceed? (y/n): y
Your call!
Query OK, 0 rows affected
Time: 0.014s
MySQL root@localhost:info> select id from member;
+----+
| id |
+----+
| 1  |
| 2  |
| 3  |
| 4  |
| 5  |
+----+
5 rows in set
Time: 0.008s
MySQL root@localhost:info> select id,name from member;
+----+----------+
| id | name     |
+----+----------+
| 1  | zhangsan |
| 2  | wangwu   |
| 3  | qianqi   |
| 4  | lisi     |
| 5  | zhaoliu  |
+----+----------+
5 rows in set
Time: 0.007s
123456789101112131415161718192021222324252627282930

(3) 创建表的时候指定索引

CREATE TABLE 表名 (字段1 数据类型,字段2 数据类型,[...],INDEX 索引名(列名));
_______________________________________________________________________
create table test(id int(4) not null,name varchar(10) not null,cardid varchar(18) not null,index id_index (id));
show create table test\G;
1234

示例:

MySQL root@localhost:info> show create table test\G;
***************************[ 1. row ]***************************
Table        | test
Create Table | CREATE TABLE "test" (
  "id" int(4) NOT NULL,
  "name" varchar(10) NOT NULL,
  "cardid" varchar(18) NOT NULL,
  KEY "id_index" ("id")
) ENGINE=InnoDB DEFAULT CHARSET=utf8

1 row in set
Time: 0.001s
123456789101112

3. 唯一索引

  • 与普通索引类似,但区别是唯一索引列的每个值都唯一
  • 唯一索引允许有空值(注意和主键不同)
  • 如果是用组合索引创建,则列值的组合必须唯一
  • 添加唯一键将自动创建唯一索引

(1) 直接创建唯一索引

CREATE UNIQUE INDEX 索引名 ON 表名(列名);
1

示例:

select * from member;
create unique index address_index on member (address);
create unique index name_index on member (name);                             1
show create table member;
1234

(2) 修改表方式创建

ALTER TABLE 表名 ADD UNIQUE 索引名 (列名);
1

示例:

alter table member add unique cardid_index (cardid);
1

(3) 创建表的时候指定

CREATE TABLE 表名 (字段1 数据类型,字段2 数据类型,[...],UNIQUE 索引名 (列名));
1

示例:

create table amd2 (id int,name varchar(20),unique id_index (id));
show creat table amd2;

create table test2 (id int,name varchar(40),age int(5),primary key (id));
1234

4. 主键索引

  • 是一种特殊的唯一索引,必须指定为 “PRIMARY KEY”
  • 一个表只能有一个主键,不允许有空值,添加主键将自动创建主键索引

(1) 创建表的时候指定

CREATE TABLE 表名 ([...],PRIMARY KEY (列名));
1

示例:

create table test1 (id int primary key,name varchar(20));
create table test2 (id int,name varchar(20),primary key (id));

show create table test1;
show create table test2;
12345

(2) 修改表方式创建

ALTER TABLE 表名 ADD PRIMARY KEY (列名);
1

5. 组合索引(单列索引与多列索引)

可以是单列上创建的索引,也可以是在多列上创建的索引。需要满足最左原则,因为 select 语句的 where 条件是依次从左往右执行的,所以在使用 select 语句查询时 where 条件使用的字段顺序必须和组合索引中的排序一致,否则索引将不会生效。

CREATE TABLE 表名 (列名1 数据类型,列名2 数据类型,列名3 数据类型,INDEX 索引名 (列名1,列名2,列名3));

select * from 表名 where 列名1='...' AND 列名2='...' AND 列名3='...';
123

示例:

create table amd1 (id int not null,name varchar(20),cardid varchar(20),index index_amd (id,name));
show create table amd1;
insert into amd1 values(1,'zhangsan','123123');
select * from amd1 where name='zhangsan' and id=1;
1234

小结:
组合索引创建的字段顺序是其触发索引的查询顺序

create table "test3" (id int(11) not null,name varchar(50) default null,age int(5) default null,key index_idname (id,name)) engine=innodb default charset=utf8;

> `对上表进行 select 查询`
select id,name from test3;		#会触发组合索引
select name,id from test3;		#按照索引从左到右检索的顺序,则不会触发组合索引
12345

6. 全文索引(FULLTEXT)

适合在进行模糊查询的时候使用,可用于在一篇文章中检索文本信息。在 MySQL5.6 版本以前 FULLTEXT 索引仅可用于 MyISAM 引擎,在 5.6 版本之后 innodb 引擎也支持 FULLTEXT 索引。全文索引可以在 CHAR、VARCHAR 或者 TEXT 类型的列上创建。每个表只允许有一个全文索引。

(1) 直接创建索引

CREATE FULLTEXT INDEX 索引名 ON 表名 (列名);
1

示例:

select * from member;
create fulltext index remark_index on member (remark);
12

(2) 修改表方式创建

ALTER TABLE 表名 ADD FULLTEXT 索引名 (列名);
1

(3) 创建表的时候指定索引

CREATE TABLE 表名 (字段1 数据类型1,[...],FULLTEXT 索引名 (列名)); 
1
数据类型可以为 CHAR、VARCHAR 或者 TEXT

(4) 使用全文索引查询

SELECT * FROM 表名 WHERE MATCH(列名) AGAINST('查询内容');
1

示例:

select * from member where match(remark) against('this is vip');
or 
select * from member where remark='this is vip';
123

7. 总结


索引分为:

  • 普通索引:针对所有字段,没有特殊的 需求/规则
  • 唯一索引:针对唯一性的字段,仅允许出现一次空值
  • 组合索引:多列/多字段 组合形式的索引
  • 全文索引:varchar char text
  • 主键索引:针对唯一性字段、且不可为空,同时一张表只允许包含一个主键索引

创建索引:

  • 在创建表的时候,直接指定 index
  • alter 修改表结构的时候,进行 add 添加 index
  • 直接创建索引 index

三、查看索引

show index from 表名;
show index from 表名\G;		#竖向显示表索引信息
show keys from 表名;
show keys from 表名\G;
1234

示例:

MySQL root@localhost:info> show index from member;
+--------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table  | Non_unique | Key_name     | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| member | 0          | cardid_index | 1            | cardid      | A         | 5           | <null>   | <null> | YES  | BTREE      |         |               |
| member | 1          | phone_index  | 1            | phone       | A         | 5           | <null>   | <null> | YES  | BTREE      |         |               |
| member | 1          | id_index     | 1            | id          | A         | 5           | <null>   | <null> | YES  | BTREE      |         |               |
+--------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

3 rows in set
Time: 0.010s
1234567891011
各字段的含义如下:
字段含义
Table表的名称
Non_unique如果索引内容唯一,则为 0;如果可以不唯一,则为 1
Key_name索引的名称
Seq_in_index索引中的列序号,从 1 开始。 limit 2,3
Column_name列名称
Collation列以什么方式存储在索引中。在 MySQL 中,有值 ‘A’(升序)或 NULL(无分类)
Cardinality索引中唯一值数目的估计值
Sub_part如果列只是被部分地编入索引,则为被编入索引的字符的数目(zhangsan)。如果整列被编入索引,则为 NULL
Packed指示关键字如何被压缩。如果没有被压缩,则为 NULL
Null如果列含有 NULL,则含有 YES。如果没有,则该列含有 NO
Index_type用过的索引方法(BTREE, FULLTEXT, HASH, RTREE)
Comment备注

四、删除索引

1. 直接删除索引

DROP INDEX 索引名 ON 表名;
1

示例:

drop index name_index on member;
1

2. 修改表方式删除索引

ALTER TABLE 表名 DROP INDEX 索引名;
1

示例:

alter table member drop index id_index;
show index from member;
12

3. 删除主键索引

ALTER TABLE 表名 DROP PRIMARY KEY;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老赵学coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值