MySQL使用联合索引功能的示例代码分享


本文摘自PHP中文网,作者黄舟,侵删。

这篇文章主要介绍了MySQL联合索引功能与用法,结合具体实例形式分析了联合索引的概念、功能、具体使用方法与相关注意事项,需要的朋友可以参考下

本文实例讲述了MySQL联合索引功能与用法。分享给大家供大家参考,具体如下:

联合索引又叫复合索引。对于复合索引:Mysql从左到右的使用索引中的字段,一个查询可以只使用索引中的一部份,但只能是最左侧部分。例如索引是key index (a,b,c). 可以支持a | a,b| a,b,c 3种组合进行查找,但不支持 b,c进行查找 .当最左侧字段是常量引用时,索引就十分有效。

两个或更多个列上的索引被称作复合索引。

利用索引中的附加列,您可以缩小搜索的范围,但使用一个具有两列的索引 不同于使用两个单独的索引。复合索引的结构与电话簿类似,人名由姓和名构成,电话簿首先按姓氏对进行排序,然后按名字对有相同姓氏的人进行排序。如果您知 道姓,电话簿将非常有用;如果您知道姓和名,电话簿则更为有用,但如果您只知道名不姓,电话簿将没有用处。

所以说创建复合索引时,应该仔细考虑列的顺序。对索引中的所有列执行搜索或仅对前几列执行搜索时,复合索引非常有用;仅对后面的任意列执行搜索时,复合索引则没有用处。

如:建立 姓名、年龄、性别的复合索引。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

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 a>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.索引越少越好

原因:主要在修改数据时,第个索引都要进行更新,降低写速度。

2.最窄的字段放在键的左边

3.避免file sort排序,临时表和表扫描.

以上就是MySQL使用联合索引功能的示例代码分享的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

一个简单的mysql数据浏览器

mysql常用的建表等sql语句写法总结

18个常用的mysql命令

mysql中各种常见join连表查询实例总结

mysql添加分区出错怎么办?

怎么将mysql服务移除?

mysql8忘记密码的快速解决方法

mysql外键约束怎么写

怎么用win r启动mysql

mysql 如何利用分片来解决 500 亿数据的存储问题

更多相关阅读请进入《mysql》频道 >>


数据库系统概念 第6版
书籍

数据库系统概念 第6版

机械工业出版社

本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...