六、mysql索引
注意:创建索引的基本原则:
1、索引要建在使用较多的字段上
2、尽量不要在相同值较多的字段上建立索引,比如姓名
3、对于经常进行数据存取的字段不要建立索引
4、对于有外键引用的表,在主键和外键上建立索引
索引类型:
1、普通索引
mysql> create index ipaddr_idx(索引名) on accesslog(ipaddr); \\添加索引 (accesslog表 在test数据库中)
mysql> alter table accesslog add index ipaddr_idx (ipaddr); \\添加索引
mysql> create table student(id int primary key,name varchar(30),sex enum('man','woman'),score float(4,1)
,addr varchar(60),index addr_idx (addr)); \\添加索引
mysql> drop index ipaddr_idx on accesslog; \\删除索引
练习:从weblog表中查找ip地址为192.168.20.171的所有行,观察创建索引前和创建索引后的区别
mysql> select * from accesslog where ipaddr='192.168.20.171';
mysql> create index ipaddr_idx on accesslog(ipaddr);
mysql> select * from accesslog where ipaddr='192.168.20.171';
由此可知,建立索引后 , 提高了查询速度
练习:观察下列查询在没有建立索引前所使用的时间和索引后所使用的时间,建立索引后下列哪些查询没有使用索引。
(1)在employees表中查询first_name以Mary开头的所有员工
(2)在employees表中查询first_name包含mar字符的员工
(3)在employees表中查询last_name以He开头的员工
(4)在employees表中查询last_name包含oo字符的员工
(1)mysql> select * from employees where first_name regexp '^Mary';
> select * from employees where first_name like 'Mary%'; 使用了索引。
mysql> create index flname_idx on employees (first_name,last_name);
mysql> explain select * from employees where first_name like 'Mary%'\G; 查看是否使用了索引。
(2)mysql> select * from employees where first_name regexp 'mar';
select * from employees where first_name like '%Mary%'; 没有使用索引。
(3)mysql> select * from employees where last_name regexp '^He'; 没有
(4)mysql> select * from employees where last_name regexp 'oo'; 没有
mysql> select * from employees where match(first_name,last_name) against('Mary');
2、唯一索引 (字段值必须唯一,但允许有空值)
mysql> create unique index id_idx on weblog(id);
3、全文索引(用于在char,varchar,text等文本类型的字段中)
mysql> create fulltext index flname_idx on employees(first_name,last_name);
4、聚集索引
对于innodb存储引擎
如果表里面包含有主键,直接使用主键做聚集索引
如果没有主键,则将第一个包含not null属性的unique index列作为聚集索引
如果前两个条件都不满足,则mysql会自动增加一个autoincrement的列作为聚集索引
5、空间索引
索引使用总结:
(1)索引一般在,<=,>=,between,in以及某些情况下的like等操作符上才能使用
(2)如果使用like,则%或_不能位于开头
(3)如果使用多列索引,则第一列必须包含匹配的条件
(4)如果在列上使用函数则不能使用索引
索引的缺点:
创建索引会占用磁盘空间,尤其是表很大且创建索引的字段值比较多且内容比较长的话更是如此
对于写入操作,如insert、update、delete等操作,索引会降低它们的速度