MYSQL如何创建索引

一、创建普通索引:

create table t1 (id int primary key, name varchar(10), sex enum('f','m','un'), index(name)) engine=myisam character set utf8;

二、创建唯一索引(同时自定义索引的名字)

create table t1 (id int primary key, name varchar(10), sex enum('f','m','un'), unique index '索引名称' (name)) engine=myisam character set utf8;

三、创建单列索引(一和二目前都是创建单列索引)

create table t1(

id int primary key,

name varchar(20),

sex enum('f','m','un'),

index 'name_in' ('name' (10)))

engine=myisam character set utf8;

括号里的10,表示该索引的长度

四、创建组合索引

create table t1(

id int primary key,

name varchar(20),

sex enum('f','m','un'),

index 'name_in' (id,name,age(100))

)

engine=myisam character set utf8;

注意:

1、以最左边作为参考,就是where中用到id有关的内容,都会使用索引,但若是where的是name和age,就不会使用到索引

mysql> explain select name,age from t4 where id<3 and age<50\G;

*************************** 1. row ***************************

id: 1

select_type: SIMPLE

table: t4

partitions: NULL

type: range

possible_keys: mutildx

key: mutildx

key_len: 5

ref: NULL

rows: 2

filtered: 33.33

Extra: Using where; Using index

1 row in set, 1 warning (0.01 sec)

ERROR:

No query specified

mysql> show create table t4\G;

*************************** 1. row ***************************

Table: t4

Create Table: CREATE TABLE `t4` (

`id` int(11) DEFAULT NULL,

`name` varchar(10) DEFAULT NULL,

`age` int(11) DEFAULT NULL,

KEY `mutildx` (`id`,`name`,`age`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1

1 row in set (0.01 sec)

ERROR:

No query specified

mysql> explain select name,age from t4 where age<50\G;

*************************** 1. row ***************************

id: 1

select_type: SIMPLE

table: t4

partitions: NULL

type: index

possible_keys: NULL

key: mutildx

key_len: 23

ref: NULL

rows: 5

filtered: 33.33

Extra: Using where; Using index

1 row in set, 1 warning (0.00 sec)

ERROR:

No query specified

五、创建全文索引

所以语句变成

fulltext index 'name' (info);

六、如何修改和删除索引

1、使用alter语句

alter table t1 add index 'nameidx' (name(20));

alter table t1 drop index 'nameidx';

2、使用create语句

create index nameidx on t1(name);

使用drop语句

drop index 'nameidx' on t1;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容