mysql索引如何使用

藏色散人
藏色散人原创
2020-09-16 09:37:566906浏览

mysql索引的使用方法:【alter table table_name add index 索引名(column)】,表示添加普通索引。mysql索引的目的在于提高查询效率。

mysql索引的目的在于提高查询效率,可以类比字典,如果要查“mysql”这个单词,我们肯定需要定位到m字母,然后从下往下找到y字母,再找到剩下的sql。如果没有索引,那么你可能需要把所有单词看一遍才能找到你想要的。

(推荐教程:mysql视频教程

在创建索引时,需要考虑哪些列会用于 SQL 查询,然后为这些列创建一个或多个索引。事实上,索引也是一种表,保存着主键或索引字段,以及一个能将每个记录指向实际表的指针。数据库用户是看不到索引的,它们只是用来加速查询的。数据库搜索引擎使用索引来快速定位记录。

mysql有四种索引(主键索引/普通索引/全文索引/唯一索引)

1.索引的添加

1.1主键索引的添加

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

create table a(  
id int primary key auto_increment,  
name varchar(20) not null default ''  
);  
//这里id就是表的主键

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

alter table table_name add primary key (column name);

1.2普通索引

普通索引一般是在建表后再添加的,

create index 索引名 on table_name(column1,column2);
alter table table_name add index 索引名(column1,column2);

1.3全文索引

首先,全文索引主要针对文本文件,比如文章,标题,全文索引只有MyISAM有效(mysql5.6之后InnoDB也支持了全文索引)

create table c(  
id int primary key auto_increment ,  
title varchar(20),  
content text,  
fulltext(title,content)  
)engine=myisam charset utf8;  
  
insert into c(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 c where content like "%mysql%";

这里并不会使用全文索引,可以用explain进行查看。正确用法:

select *  from c where match(title,content) against ('MYSQL');

备注:

1. 在mysql中fulltext 索引只针对 myisam生效

2. mysql自己提供的fulltext针对英文生效->sphinx(coreseek)技术处理中文

3. 使用方法是 match(字段名..) against(‘关键字’)

1.4唯一索引

create table d(id int primary key auto_increment , name varchar(32) unique)

d表中name就是唯一索引,唯一索引可以有多个null,不能是重复的内容

相比主键索引,主键字段不能为null,也不能重复

2. 查询索引

show indexes from table_name;
show keys from table_name;

3.删除索引

alter table table_name drop index 索引名;

以上就是mysql索引如何使用的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。