MySQL Optimization Part 3 - Indexes Operations

MySQL Optimization Part 3 - Indexes Operations

目录


索引

说起提高数据库性能,索引是最物美价廉的东西了。不用加内存,不用改程序,不用调sql,只要执行个正确的 create index,查询速度就可能提高百倍千倍,这可真有诱惑力。可是天下没有免费的午餐,查询速度的提高是以插入、更新、删除的速度为代价的,这些写操作,增加了大量的I/O。

一般情况下,有四种索引 (复合索引不算在内):主键索引/唯一索引/全文索引/普通索引。
下面来说说四种索引的增删改查。

创建索引后,为什么查询会变快:因为由 BTREE 上的指针直接指向具体的数据行,指针操作当然快啦。


添加索引

主键索引

当一张表,把某个列设为主键的时候,则该列就是主键索引。

create table table_a(
id int unsigned primary key auto_increment,
name varchar(32) not null defaul '');
/*这时 id 列就是主键索引.*/

如果创建表时没有指定主键索引,也可以在创建表后,再添加,指令如下:

alter table tablename add primary key (columnname);
create table table_b (id int , name varchar(32) not null default ‘’);

alter table table_b add primary key (id);

普通索引

一般来说,普通索引的创建,是先创建表,然后再创建普通索引。

create table table_c(
id int unsigned,
name varchar(32)
)

create index indexname on tablename (column1,column2);

全文索引

全文索引,主要是针对对文件,文本的检索, 比如文章, 全文索引针对MyISAM有用.

创建:

CREATE TABLE articles (
       id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,
       title VARCHAR(200),
       body TEXT,
       FULLTEXT (title,body)
     )engine=myisam charset utf8;

INSERT INTO articles (title,body) VALUES
     ('MySQL Tutorial','DBMS stands for DataBase ...'),
     ('How To Use MySQL Well','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 ...');

如何使用全文索引:

#错误用法,不会使用到全文索引
select * from articles where body like '%mysql%'; 
#证明:
explain  select * from articles where body like '%mysql%'

#正确的用法是:
select * from articles where match(title,body) against('database'); 

说明

  • 在mysql中 fulltext 索引只针对 myisam生效
  • mysql自己提供的fulltext针对英文生效->sphinx (coreseek) 技术处理中文
  • 使用方法是 match(字段名..) against(‘关键字’)
  • 全文索引一个 叫 停止词, 因为在一个文本中,创建索引是一个无穷大的数,因此,对一些常用词和字符,就不会创建,这些词,称为停止词。

唯一索引

创建方式1

#当表的某列被指定为unique约束时,这列就是一个唯一索引
create table table_d(
id int primary key auto_increment,
name varchar(32) unique);

#这时, name 列就是一个唯一索引.

unique 字段可以为NULL,并可以有多NULL, 但是如果是具体内容,则不能重复.

主键字段,不能为NULL,也不能重复.

创建方式2

#在创建表后,再去创建唯一索引
create table table_e(
id int primary key auto_increment, 
name varchar(32));

create unique index indexname on tablename (columns..);

查询索引

三种方式

# 缺点:不能够显示索引的名字
desc tablename\G
show index(es) from tablename\G
show keys from tablename\G

删除索引

drop index indexname on tablename;
alter table tablename drop index indexname; 

修改索引

先删除,再重新创建

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章