SQL查询优化: 既有Unique Index为何还要另加Index?

在使用 -GWA2 进行WebApp开发时,我们创建基于MySQL的相关数据表时,都会有意识地在数据表的关键字段上增加索引,以期待查询时能够较快地返回结果集。

在我们现有的生产线上的数据观测中,同样一张数据表,通常当数据达到10M+时,如果某个待检索字段(用在Where里作为查询字段)没有使用索引,一次查询大约需要耗时50s+,如果增加了相应的索引,则单次查询大约耗时5s左右,性能提升10倍以上。

所以,理论联系实际,我们都应该在相关待检索的字段上增加索引,这次要提及和澄清的是增加Unique Index还是Index? 只增加Unique Index,还是Index即可?或者两种Index都需要? 在检索方面,Unique Index保持了数据的唯一性,实际兼有Index的功能,在被检索时提供同样的优化性能。

情况稍微复杂一些的例子是这样,当一个Unique Index增加到多个字段的组合上时,其Index的作用并不能想当然地将Index效果追加到每一个组合中的字段上。如下是 -MySQL 官方文档对于组合字段的Unique Index的描述。

-R/u2SN  ) “If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1)(col1, col2), and (col1, col2, col3).
MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index. ”

用简略地话来说,Unique Index的Index作用:1)当只有一个字段时,其Index作用也同样地施加到该字段上;2)当为多个字段的组合时,其Index的作用,只施加到组合的第一个字段上。

所谓差之毫厘,谬之千里。当待检索的字段是某个Unique Index的组合字段之一,且不是第一个时,被用做Where的查询条件,查询性能将急剧下降,每次皆是全表扫描,逐行对比。

这种性能隐患,在开发初期并不容易发现,只有当数据量级增长到10M+时,查询耗时才会逐步显现出来。

 

gwa2-logo-201606.v2

-GWA2 是”通用网络应用架构( General Web Application Architeture )”,基于 -GWA2 可以轻便构建各种网络应用程序, 
包括复杂的在线购物商城、 旅游交易平台、社群或者社交网站和新闻资讯网站等, 
也包括各种企事业单位网上门户,在线交互及服务作业系统等. 
还可以包括为NativeApp做服务器端支持, 甚至是WebApp的全部.
-GWA2 是为数不多的支持跨开发语言的应用框架,目前支持 -Java, -PHP, -Perl, -Aspx and -Python .
-GWA2 is a “General Web Application Architecture”, and based on -GWA2 developers can easily build a variety of network applications,
Including complex online shopping malls, travel trading platforms, community or social networking sites and news information sites, etc.
Also the applications include various enterprises and institutions online portals, online interaction and service operations systems.
And it also includes server-side support for NativeApp, or even all of the WebApp.
-GWA2 is one of the web frameworks which provide cross-language support for -Java, -PHP, -Perl, -Aspx and -Python at present.

-GWA2 is E.A.S.Y 
Easy Along, Swift Yield
轻松启动, 快速产出. 

此条目发表在-GWA2, 服务器运维, 计算机技术分类目录,贴了, , , , , 标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code