MySQL学习database相关

MySQL 索引学习笔记

2016-11-03  本文已影响127人  专职跑龙套

索引的作用:空间换时间,加快查询的速度。

select * from student where name = 'Tom'

索引的创建:基于某一列创建,由某一列上的数据组成。

create index <index_name> on students(name)

详细的语法:

CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
[index_type]
ON tbl_name (index_col_name,...)
[index_option]
[algorithm_option | lock_option] ...

索引的数据结构

有的情况下即使定义了索引也不会使用:

where name != 'Tom'
where name <> 'Tom'
where name not in ('Tom', 'Lily')
where name like '%To%' // %出现在最左边,无法进行比较

联合索引 Composite Index:

create index <index_name> on students(name, age, address)

对于联合索引,只有符合最左前缀的查询才会被优化:

where name = 'Tom'  // 优化
where name = 'Tom' and age = '12'  // 优化
where age = '12'  // 不优化
where age = '12' and address='Shanghai'  // 不优化

前缀索引:
假设students表包括 first_name 和 last_name:

不需要建立索引的情况:

一些注意事项:

select * from students where first_name = 'San' and last_name = 'Zhang'; // 推荐使用
select * from students where first_name || last_name = 'San Zhang'; // 不推荐使用
where age != '20' // 不推荐使用
where age < '20' or age > '20' // 推荐使用

引用:
MySQL 官网

上一篇 下一篇

猜你喜欢

热点阅读