Home > Database > Mysql Tutorial > body text

辛星让mysql跑得更快第二节之索引上部分_MySQL

WBOY
Release: 2016-06-01 13:02:03
Original
1052 people have browsed it

如果把我们的数据库信息当做一本书或者一个字典,那么索引可以理解为它的目录,如果我们创建一个优秀的目录,那么我们检索信息就会快得多,如果我们创建一个渣渣索引,也有可能拖垮整个系统。

索引我们分为四类,通常分为四大类型,即主键索引、全文索引、唯一索引、普通索引,这是按照索引的类型来分的。所谓主键索引,那就是当我们创建一张表的时候,如果我们指定了一个主键,那么它就自动成为主键索引,比如SQL语句如下(这里的id就自动成为了主键索引):

create table xin(id int unsigned primary key auto_increment,
		name   varchar(32) not null default '');
Copy after login

一般来说,对于普通索引,我们可以在创建表的时候指定索引,也可以在创建表的时候指定索引,下面我们以县创建表然后再添加索引为例,看代码:

#创建一个数据表
create table xin(id int unsigned,
	name   varchar(32) not null default '');

#在该表上创建一个索引
create index xiaohei  on xin(id);
Copy after login
这里说一下把,这里的添加索引的格式是:create index 索引名 on 表名(列名);

然后说一下全文索引,所谓全文索引,主要是从数据库中搜索字符串信息的,比如我们逛很多论坛,它的搜索功能就特别需要全文索引了,我们的全文索引主要针对文件、文本的索引,而且目前来说,全文索引依然只对引擎MyIASM有效,咱们指定一下表的引擎就可以了,看下面代码:

#创建一个文章表,并且设置索引
create table article(id int primary key,
	title varchar(200) not null ,
	body  text,
	fulltext(title,body)
) engine = myisam ;
Copy after login
那么我们使用该全文索引的时候应该使用使用match和against,看下面操作:
#按照这种方式我们可以快速的使用全文索引来查找内容
select * from article where match(title,body)  against ('xin');
Copy after login
但是mysql自带的这个全文索引并不支持中文,我们可以考虑使用sphinx来支持中文,这里先不介绍。

对于unique索引,也就是唯一索引,我们直接在在列级完整性约束后面加一个unique即可,这里需要注意的是被unique修饰的字段是可以为空的,而且是可以有多个为空的,当然也可以像创建一个普通index那样去创建,但是此时的index必须在前面加上一个unique修饰符。

对于索引的删除,可以使用【alter table 表名 drop index 索引名】,但是我感觉我们使用【drop index 索引名 on 表名】更好一些。

那么我们怎么看一个表的索引呢,我们可以用【desc 表名】的方式来查看索引,我们还可以使用【show index from 表名】或者【show index from 表名】来查看一个表的索引。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!