索引是一个单独的数据结构,通过对一列或多列进行组织,可以快速定位记录。
提高了查询速度(以及分组、排序速度),但是增加了存储,降低了更新速度。
mysql支持btree索引。
还可以定义唯一索引(允许为空)、主键(唯一非空索引)
索引遵循最左前缀原则,即多列索引只有使用定义左边的字段才有效。
索引不要太多,索引定义的列不要太多,经常更新的表要减少索引,数据量邵的表不见得需要索引,不同值少的列不要建立索引。
创建索引
创建表时创建索引
[unique|fulltext|sparial] (index|key) (index_name) (col_name1[length][,column_name2]) (asc|desc)
drop table if exists tb_emp1;
create table tb_emp1(
id int ,
name varchar(10),
index a(id)
);
insert into tb_emp1(id,name) values('1','a');
insert into tb_emp1(id,name) values('2','b');
insert into tb_emp1(id,name) values('3','c');
insert into tb_emp1(id,name) values('4','d');
insert into tb_emp1(id,name) select id+4,name from tb_emp1;
explain select * from tb_emp1 where id=1;
1 SIMPLE tb_emp1 ref id id 5 const 1 100.00
drop table if exists tb_emp1;
create table tb_emp1(
id int ,
name varchar(10)
);
insert into tb_emp1(id,name) values('1','a');
insert into tb_emp1(id,name) values('2','b');
insert into tb_emp1(id,name) values('3','c');
insert into tb_emp1(id,name) values('4','d');
insert into tb_emp1(id,name) select id+4,name from tb_emp1;
explain select * from tb_emp1 where id=1;
1 SIMPLE tb_emp1 ALL 8 12.50 Using where
drop table if exists tb_emp1;
create table tb_emp1(
id int primary key,
name varchar(10)
);
insert into tb_emp1(id,name) values('1','a');
insert into tb_emp1(id,name) values('2','b');
insert into tb_emp1(id,name) values('3','c');
insert into tb_emp1(id,name) values('4','d');
insert into tb_emp1(id,name) select id+4,name from tb_emp1;
explain select * from tb_emp1 where id=1;
给已存在的表创建索引
ALTER TABLE table_name ADD [unique|fulltext|sparial] (index|key) (index_name) (col_name1[length][,column_name2]) (asc|desc)
drop index index_name on table_name;
drop table if exists tb_emp1;
create table tb_emp1(
id int ,
name varchar(10)
);
alter table tb_emp1 add index (id,name);
insert into tb_emp1(id,name) values('1','a');
insert into tb_emp1(id,name) values('2','b');
insert into tb_emp1(id,name) values('3','c');
insert into tb_emp1(id,name) values('4','d');
insert into tb_emp1(id,name) select id+4,name from tb_emp1;
show index from tb_emp1;
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment Index_comment Visible Expression
Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment Index_comment Visible Expression tb_emp1 1 id 1 id A 2 YES BTREE YES
tb_emp1 1 id 2 name A 2 YES BTREE YES
drop index id on tb_emp1;