MySQL优化 之 索引

四种索引(主键索引,唯一索引,普通索引,全文索引)
【对查询语句会提高效率】
【对增删改语句会降低效率,因为还要对索引进行增删改!】
【创建索引会占磁盘空间】
【对频繁查询的字段应创建索引,对频繁更新的字段不适合创建索引】


1、添加


1.1------------------主键索引添加------------------
@1.当一张表,把某个列设为主键的时候,则该列就是主键索引
create table emp(
id int primary key auto_increment,
name varchar(32) not null default ''
);
这里id列就是主键索引


@2.创建表时没有指定主键,则
alter table emp add primary key(empno);


1.2------------------普通索引添加------------------
一般来说,普通索引是在创建表后,再创建普通索引的
比如:
create table aaa(
id int,
name varchar(32)
);
create index 索引名 on 表(列);
create index my_index on aaa(name);


1.3------------------唯一索引添加------------------
@1.建表时,创建唯一索引
create table ddd(
id int primary key auto_increment,
name varchar(32) unique
);


insert into ddd value (1,'sss');
insert into ddd value (2,'sss'); 【这里拒绝插入!因为添加了unique唯一索引】
insert into ddd value (3,null);
insert into ddd value (4,null); 【但这里可以,允许多个null】


@2.建表后,创建唯一索引
create table eee(
id int primary key auto_increment,
name varchar(32)
);
create unique index my_unique on eee(name);


1.4------------------全文索引添加------------------
主要是针对对文件、文本的检索,比如文章,
【且只针对MyISAM有效!】


创建方法,建表时创建
create table articles (
id int  auto_increment not null primary key,
title varchar(200),
content text,
FULLTEXT (title,content)
)ENGINE  =  MYISAM  CHARACTER  SET utf8;


插入数据作测试
INSERT INTO articles (title,content) 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 content like '%mysql%';   【没有用到全文索引!】
正确用法:
select * from articles where match(title,content) against('configured');
select * from articles where match(title,content) against('database');
select * from articles where match(title,content) against('root');
select match(title,content) against('root') from articles; #可以查看匹配度


全文索引说明:
1.fulltext索引只对myisam有效
2.fulltext针对英文有效【中文的话要用sphinx,所以fulltext索引了解即可】
3.全文索引一个 叫 停止词,就是对一些词不会创建全文索引的,就叫停止词
例如
select * from articles where match(title,content) against('a');
select * from articles where match(title,content) against('mysql');
返回结果都为空,因为这些词出现频繁,如果都创建全文索引,
那么索引会无穷大,不科学!这些就叫停止词。


2、查询
如下几种方法:
desc emp;   (缺点:不能显示索引名)
show index from emp\G
show indexes from emp\G
show keys from emp\G


3、删除
-----------删除索引-----------
drop index 索引名 on 表名;
或者
alter table 表名 drop index 索引名;
-----------删除主键-----------
alter table 表名 drop primary key; 


4、修改


先删除,再创建索引!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值