『SQL』索引特性

提高数据库的性能,索引是物美价廉的东西。不用加内存,不用改程序,不用调sql,只要执行正确的create index,查询速度就可能提高成百上千倍。但是天下没有免费的午餐,查询速度的提高是以插入、更新、删除的速度为代价的,这些写操作,增加了大量的IO。所以它的价值,在于提高一个海量数据的检索速度。

先来看一个例子
创建一个有海量数据的表,观察一下没有索引时的查询速度

--构建一个8000000条记录的数据

--构建的海量表数据需要有差异性,所以使用存储过程来创建, 拷贝下面代码就可以了,暂时不用理解
-- 产生随机字符串
delimiter $$
create function rand_string(n INT)
returns varchar(255)
begin
declare chars_str varchar(100) default
'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
declare return_str varchar(255) default '';
declare i int default 0;
while i < n do
set return_str = concat(return_str, substring(chars_str, floor(1 + rand() * 52), 1));
set i = i + 1;
end while;
return return_str;
end $$
delimiter ;

--产生随机数字
delimiter $$
create function rand_num()
returns int(5)
begin
declare i int default 0;
set i = floor(10 + rand() * 500);
return i;
end $$
delimiter ;

--创建存储过程,向雇员表添加海量数据
delimiter $$
create procedure insert_emp(in start int(10), in max_num int(10))
begin
declare i int default 0;
set autocommit = 0;
repeat
set i = i + 1;
insert into EMP values ((start+i)
,rand_string(6), 'SALESMAN', 0001, curdate(), 2000, 400, rand_num());
until i = max_num
end repeat;
commit;
end $$
delimiter ;

-- 执行存储过程,添加8000000条记录
call insert_emp(100001, 8000000);

如果出现下述报错,可将表名emp修改为EMP
在这里插入图片描述
由于数据量过大,所以需要多等待一会儿
在这里插入图片描述
海量数据的表已经创建好,下面来实际查询测试一下

  • 查询员工编号为998877的员工
    在这里插入图片描述
    从上述查询结果可以看到,耗时6.07秒,这还是本机一个人在操作,在实际项目中,如果放在公网中,假如同时有1000个人并发查询,很可能就会死机
  • 解决方法,创建索引,测试一下查询时间
    在这里插入图片描述
    从上述结果可以看出,创建了索引后,查询员工只需要0.00秒
  • 我们再使用ename字段进行查询
    在这里插入图片描述
    从上述查询结果可以看出,还是很慢,这是因为前面只是对empno建立了索引,并没有为ename创建索引
  • 我们为ename字段建立索引再来查询一下
    在这里插入图片描述
    在这里插入图片描述

基本原理

在这里插入图片描述
注意

  • 索引会占用磁盘空间
  • 添加一条记录,除了添加到表中,还要维护二叉树,速度有影响,但不大。
  • 当我们添加一条索引,不能解决所有查询问题,需要分别给字段建立索引;例如select * from EMP where ename = ‘abcdef’;
  • 索引是以空间换时间

创建索引

常见的索引

  • 主键索引(primary key)
  • 唯一索引(key)
  • 普通索引(index)
  • 全文索引(fulltext)

创建主键索引。

方法一

-- 在创建表的时候,直接在字段名后制定primary key
create table table_name(
	id int primary key, 
	name varchar(20)
);

方法二

-- 在创建表的最后,制定某列或某几列为主键索引
create table table_name(
	id int, 
	name varchar(20), 
	primary key(id)
);

方法三

-- 创建表以后再添加主键
create table table_name(
	id int, 
	name varchar(20)
);

alter table table_name add primary key(id);

主键索引的特点

  • 一个表中,最多有一个主键索引,当然可以使用复合主键
  • 主键索引的效率高(主键不可重复)
  • 创建主键索引时,它的值不能为null,且不能重复
  • 主键索引的列基本上是int

创建唯一索引

方法一

-- 在表定义时,在某列后直接制定unique属性
create table table_name(
	id int primary key, 
	name varchar(20) unique
);

方法二

-- 创建表时,在表的后面制定某列或某几列为unique
create table table_name(
	id int primary key, 
	name varchar(20),  
	unique(name)
);

方法三

-- 创建表以后,再添加唯一索引
create table table_name(
	id int primary key, 
	name varchar(20)
);

alter table table_name add unique(name);

唯一索引的特点

  • 一个表中,可以有多个唯一索引
  • 查询效率高
  • 如果在一列建立唯一索引,必须保证这列不能有重复数据
  • 如果一个唯一索引上指定not null,等价于主键索引

创建普通索引

方法一

-- 在表的创建最后,制定某列为索引
create table table_name(
	id int primary key, 
	name varchar(20), 
	email varchar(30), 
	index(name)
);

方法二

-- 创建表之后,制定某列为普通索引
create table table_name(
	id int primary key, 
	name varchar(20), 
	email varchar(30)
);

alter table table_name add index(name);

方法三

-- 创建一个索引名为idx_name的索引
create table table_name(
	id int priamry key, 
	name varchar(20), 
	email varchar(30)
);

create index idx_name on table_name(name);

普通索引的特点

  • 一个表中可以有多个普通索引,普通索引在实际开发中用的比较多
  • 如果某列需要创建索引,但是该列有重复的值,那么我们就应该使用普通索引

创建全文索引

当对文章字段或有大量文字的字段进行检索时,会使用全文索引。MySQL提供全文索引机制,但是有要求,要求表的存储引擎必须是MyISAM,而且默认的全文索引只支持英文,不支持中文。如果要对中文进行全文索引,可以使用sphinx的中文版(coreseek)。
示例如下
先创建一张表

create table articles(
	id int unsigned primary key not null auto_increment, 
	title varchar(20) not null, 
	body text, 
	fulltext(title, body)
) engine = MyISAM;

插入几条数据

insert into articles(title, body) values
	('MySQL Tutorial','DBMS stands for DataBase ...'),
	('How To Use MySQL','After you went through a ...'),
	('Optimizing MySQL','In this tutorial we will show ...'),
	('1001 MySQL Tricks','1. Never run mysqld as root. 2. ...'),
	('MySQL vs. YourSQL','In the following database comparison ...'),
	('MySQL Security','When configured properly, MySQL ...');

查询包含关键字database的数据

MariaDB [lab330]> select * from articles where body like '%database%';
+----+-------------------+------------------------------------------+
| id | title             | body                                     |
+----+-------------------+------------------------------------------+
|  1 | MySQL Tutorial    | DBMS stands fro database ...             |
|  2 | MySQL Tutorial    | DBMS stands for DataBase ...             |
|  6 | MySQL vs. YourSQL | In the following database comparison ... |
+----+-------------------+------------------------------------------+
3 rows in set (0.00 sec)

使用explain工具看一下,是否使用到了索引

MariaDB [lab330]> explain select * from articles where body like '%database%'\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: articles
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 7
        Extra: Using where
1 row in set (0.00 sec)

从上述结果可以看出,key为NULL,表示没有用到全文索引
全文索引的使用

MariaDB [lab330]> select * from articles
    -> where match(title, body) against('database');
+----+-------------------+------------------------------------------+
| id | title             | body                                     |
+----+-------------------+------------------------------------------+
|  6 | MySQL vs. YourSQL | In the following database comparison ... |
|  1 | MySQL Tutorial    | DBMS stands fro database ...             |
|  2 | MySQL Tutorial    | DBMS stands for DataBase ...             |
+----+-------------------+------------------------------------------+
3 rows in set (0.00 sec)

通过explain来看一下,是否使用了索引

MariaDB [lab330]> explain select * from articles 
    -> where match(title, body) against('database') \G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: articles
         type: fulltext
possible_keys: title
          key: title
      key_len: 0
          ref: 
         rows: 1
        Extra: Using where
1 row in set (0.00 sec)

从上述结果可以看出,key使用了title,表示用到了索引

查询索引

方法一

MariaDB [lab330]> show keys from articles\G;
*************************** 1. row ***************************
		-- 表名
        Table: articles
   -- 0表示唯一索引
   Non_unique: 0
   	 -- 主键索引
     Key_name: PRIMARY
 Seq_in_index: 1
  -- 索引在哪
  Column_name: id
    Collation: A
  Cardinality: 7
     Sub_part: NULL
       Packed: NULL
         Null: 
   -- 二叉树形式的索引
   Index_type: BTREE
      Comment: 
Index_comment: 
*************************** 2. row ***************************
        Table: articles
   Non_unique: 1
     Key_name: title
 Seq_in_index: 1
  Column_name: title
    Collation: NULL
  Cardinality: NULL
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: FULLTEXT
      Comment: 
Index_comment: 
*************************** 3. row ***************************
        Table: articles
   Non_unique: 1
     Key_name: title
 Seq_in_index: 2
  Column_name: body
    Collation: NULL
  Cardinality: NULL
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: FULLTEXT
      Comment: 
Index_comment: 
3 rows in set (0.00 sec)

方法二

MariaDB [lab330]> show index from articles\G;
*************************** 1. row ***************************
        Table: articles
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: id
    Collation: A
  Cardinality: 7
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 
*************************** 2. row ***************************
        Table: articles
   Non_unique: 1
     Key_name: title
 Seq_in_index: 1
  Column_name: title
    Collation: NULL
  Cardinality: NULL
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: FULLTEXT
      Comment: 
Index_comment: 
*************************** 3. row ***************************
        Table: articles
   Non_unique: 1
     Key_name: title
 Seq_in_index: 2
  Column_name: body
    Collation: NULL
  Cardinality: NULL
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: FULLTEXT
      Comment: 
Index_comment: 
3 rows in set (0.00 sec)

方法三

MariaDB [lab330]> desc articles;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| title | varchar(20)      | NO   | MUL | NULL    |                |
| body  | text             | YES  |     | NULL    |                |
+-------+------------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

删除索引

方法一

-- 删除主键索引	
alter table table_name drop primary key;

方法二

-- 删除其他索引
alter table table_name drop index index_name;

方法三

-- 删除其他索引
drop index name on table_name;

索引创建规则

  • 比较频繁作为查询条件的字段应该创建索引
  • 唯一性太差的字段不适合单独创建索引,即使频繁作为查询条件
  • 更新非常频繁的字段不适合创建索引
  • 不会出现在where子句中的字段不应该创建索引
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值