在建立索引时,须要斟酌哪些列会用于 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索引怎样运用?的细致内容,更多请关注ki4网别的相干文章!