本文摘自PHP中文网,作者藏色散人,侵删。
mysql索引的使用方法:【alter table table_name add index 索引名(column)】,表示添加普通索引。mysql索引的目的在于提高查询效率。

mysql索引的目的在于提高查询效率,可以类比字典,如果要查“mysql”这个单词,我们肯定需要定位到m字母,然后从下往下找到y字母,再找到剩下的sql。如果没有索引,那么你可能需要把所有单词看一遍才能找到你想要的。
(推荐教程:mysql视频教程)
在创建索引时,需要考虑哪些列会用于 SQL 查询,然后为这些列创建一个或多个索引。事实上,索引也是一种表,保存着主键或索引字段,以及一个能将每个记录指向实际表的指针。数据库用户是看不到索引的,它们只是用来加速查询的。数据库搜索引擎使用索引来快速定位记录。
mysql有四种索引(主键索引/普通索引/全文索引/唯一索引)
1.索引的添加
1.1主键索引的添加
当一张表,把某个列设为主键的时候,则该列就是主键索引
1 2 3 4 5 | create table a(
id int primary key auto_increment,
name varchar(20) not null default ''
);
|
如果当创建表时没有指定主键索引,也可以在创建表之后添加:
1 | alter table table_name add primary key (column name);
|
1.2普通索引
普通索引一般是在建表后再添加的,
1 2 | create index 索引名 on table_name(column1,column2);
alter table table_name add index 索引名(column1,column2);
|
1.3全文索引
首先,全文索引主要针对文本文件,比如文章,标题,全文索引只有MyISAM有效(mysql5.6之后InnoDB也支持了全文索引)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 ...' );
|
使用全文索引常见的错误:
1 | select * from c where content like "%mysql%" ;
|
这里并不会使用全文索引,可以用explain进行查看。正确用法:
1 | select * from c where match(title,content) against ( 'MYSQL' );
|
备注:
1. 在mysql中fulltext 索引只针对 myisam生效
2. mysql自己提供的fulltext针对英文生效->sphinx(coreseek)技术处理中文
3. 使用方法是 match(字段名..) against(‘关键字’)
1.4唯一索引
1 | create table d(id int primary key auto_increment , name varchar(32) unique)
|
d表中name就是唯一索引,唯一索引可以有多个null,不能是重复的内容
相比主键索引,主键字段不能为null,也不能重复
2. 查询索引
1 2 | show indexes from table_name;
show keys from table_name;
|
3.删除索引
1 | alter table table_name drop index 索引名;
|
以上就是mysql索引如何使用的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
mysql如何实现负数转正数
mysql怎么导出用户权限
mysql中表分区的详细介绍
linux下怎么打开mysql数据库
mysql常用sql语句汇总
聊聊mysql 中常用的日期相关函数
mysql怎样防止sql注入问题
通过两种方式增加从库——不停止mysql服务
mysql求长度的函数是什么?
mysql索引那些事
更多相关阅读请进入《mysql》频道 >>
机械工业出版社
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。
转载请注明出处:木庄网络博客 » mysql索引如何使用