MySQL单列索引和组合索引
2016-04-14 13:21
701 查看
单列索引,顾名思义也就是只有一个字段的索引列。
组合索引,又称复合索引,两个或更多个列上的索引被称作复合索引。对于复合索引,他们都遵循左侧原则,也是就是说一个查询可以只使用复合索引最左侧的一部份。例如索引是key index (a,b,c). 可以支持a | a,b| a,b,c 3种组合进行查找,但不支持 b,c进行查找 .当最左侧字段是常量引用时,索引就十分有效。
假如:我们有如下的一个表结构:
那么我们看一下下列语句:
优: select * from test where a=10 and b>50
差: select * from test where b = 50
优: select * from test order by a
差: select * from test order by b
差: select * from test order by c
优: select * from test where a=10 order by a
优: select * from test where a=10 order by b
差: select * from test where a=10 order by c
优: select * from test where a>10 order by a
差: select * from test where a>10 order by b
差: select * from test where a>10 order by c
优: select * from test where a=10 and b=10 order by a
优: select * from test where a=10 and b=10 order by b
优: select * from test where a=10 and b=10 order by c
优: select * from test where a=10 and b=10 order by a
优: select * from test where a=10 and b>10 order by b
差: select * from test where a=10 and b>10 order by c
观察上诉语句,我们得出如下结论:
1. ORDER BY 中的字段必须按照SQL语句中的顺序来建索引;
2. ORDER BY 中的字段的排序顺序必须一直,否则索引无效。
3. 建了索引不一定就有效,用实际的SQL检查一下。
我们再说说索引应该遵循的原则:
1.索引越少越好 。
原因:主要在修改数据时,第个索引都要进行更新,降低写速度。
2.最窄的字段放在键的左边
3.避免file sort排序,临时表和表扫描.
组合索引,又称复合索引,两个或更多个列上的索引被称作复合索引。对于复合索引,他们都遵循左侧原则,也是就是说一个查询可以只使用复合索引最左侧的一部份。例如索引是key index (a,b,c). 可以支持a | a,b| a,b,c 3种组合进行查找,但不支持 b,c进行查找 .当最左侧字段是常量引用时,索引就十分有效。
假如:我们有如下的一个表结构:
create table test( a int, b int, c int, KEY a(a,b,c) );
那么我们看一下下列语句:
优: select * from test where a=10 and b>50
差: select * from test where b = 50
优: select * from test order by a
差: select * from test order by b
差: select * from test order by c
优: select * from test where a=10 order by a
优: select * from test where a=10 order by b
差: select * from test where a=10 order by c
优: select * from test where a>10 order by a
差: select * from test where a>10 order by b
差: select * from test where a>10 order by c
优: select * from test where a=10 and b=10 order by a
优: select * from test where a=10 and b=10 order by b
优: select * from test where a=10 and b=10 order by c
优: select * from test where a=10 and b=10 order by a
优: select * from test where a=10 and b>10 order by b
差: select * from test where a=10 and b>10 order by c
观察上诉语句,我们得出如下结论:
1. ORDER BY 中的字段必须按照SQL语句中的顺序来建索引;
2. ORDER BY 中的字段的排序顺序必须一直,否则索引无效。
3. 建了索引不一定就有效,用实际的SQL检查一下。
我们再说说索引应该遵循的原则:
1.索引越少越好 。
原因:主要在修改数据时,第个索引都要进行更新,降低写速度。
2.最窄的字段放在键的左边
3.避免file sort排序,临时表和表扫描.
相关文章推荐
- MySQL数据库备份和恢复
- 如何进行mysql日志查询
- mysql 备份 还原
- Mysql 自增长字段重置为1
- mysql5.7 修改root密码登录
- OS X平台上MySQL环境搭建
- windows下MySQL 5.7.3.0安装配置图解教程(安装版)
- MySQL入门教程(五)之表的创建、修改和删除
- MySql如何编写高效的SQL
- mysql创建用户和数据库、授权
- mysql语法 -- concat函数
- Mac安装mysql遇到的坑
- MySQL基础十:MySQL图形管理工具
- mysql数据字段加密
- MySql 优化
- Mysql存储过程使用多个游标的处理
- Mysql insert select批量插入
- mysql解压版安装
- 忘记mysql数据库root密码
- 非常简单的mysql数据库连接池