mysql四种索引

版权声明:转载请标识 https://me.csdn.net/wanghaitao4j https://blog.csdn.net/wanghaitao4j/article/details/83019981

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

 

  1. 添加

 

1.1主键索引添加

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

create table aaa

(id int unsigned primary key auto_increment ,

name varchar(32) not null defaul ‘’);

这是id 列就是主键索引.

 

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

alter table 表名 add primary key (列名);

 

举例:

create table bbb (id int , name varchar(32) not null default ‘’);

alter table bbb add primary key (id);

 

1.2普通索引

一般来说,普通索引的创建,是先创建表,然后在创建普通索引

比如:

create table ccc(

id int unsigned,

name varchar(32)

)

 

create index 索引名 on 表 (列1,列名2);

 

1.3创建全文索引

全文索引,主要是针对对文件,文本的检索, 比如文章, 全文索引针对MyISAM有用.

创建 :

CREATE TABLE articles (

       id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,

       title VARCHAR(200),

       body TEXT,

       FULLTEXT (title,body)

     )engine=myisam charset utf8;

 

INSERT INTO articles (title,body) 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 articles where body like ‘%mysql%’; 【不会使用到全文索引,具体原因看索引失效文章】

证明:

explain  select * from articles where body like ‘%mysql%’ 【explain的解释看explain的文章】

 

正确的用法是:

select * from articles where match(title,body) against(‘database’); 【可以】

 

☞ 说明:

  1. 在mysql中fulltext 索引只针对 myisam生效
  2. mysql自己提供的fulltext针对英文生效->sphinx (coreseek) 技术处理中文
  3. 使用方法是 match(字段名..) against(‘关键字’)
  4. 全文索引一个 叫 停止词,  因为在一个文本中,创建索引是一个无穷大的数,因此,对一些常用词和字符,就不会创建,这些词,称为停止词.

 

1.4唯一索引

①当表的某列被指定为unique约束时,这列就是一个唯一索引

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

 

这时, name 列就是一个唯一索引.

unique字段可以为NULL,并可以有多NULL, 但是如果是具体内容,则不能重复.

主键字段,不能为NULL,也不能重复.

 

②在创建表后,再去创建唯一索引

create table eee(id int primary key auto_increment, name varchar(32));

 

create unique index 索引名  on 表名 (列表..);

 

查询索引

desc 表名 【该方法的缺点是: 不能够显示索引名.】

show index(es) from 表名

show keys from 表名

 

删除

alter table 表名 drop index 索引名;

如果删除主键索引。

alter table 表名 drop primary key       [这里有一个小问题]

 

修改

先删除,再重新创建.

 

为什么创建索引后,速度就会变快?

猜你喜欢

转载自blog.csdn.net/wanghaitao4j/article/details/83019981