专注于云服务器
VPS主机优惠测评
国内免备案虚拟主机

mysql索引如何使用

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

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索引如何使用的详细内容,更多请关注名铺123其它相关文章!

赞(0) 打赏
转载请注明出处:晓波笔记 » mysql索引如何使用
分享到: 更多 (0)
megalayer云服务器

raksmart云服务器

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

晓波笔记-VPS主机,云服务器优惠促销测评

QQ:87304394

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏