search
HomeDatabaseMysql Tutorial数据库索引学习科学建立索引,提高查询速度

数据库索引学习科学建立索引,提高查询速度

Jun 07, 2016 pm 03:11 PM
ssqlstudyEstablishimprovedatabaseInquirescienceindexspeed

SQL Sever数据库 中巧妙地 建立索引 能起到事半功倍的效果,笔者在工作实践中发现,不良的SQL往往来自于不恰当的索引设计、不充份的连接条件和不可优化的where子句。在对它们进行适当的优化后,其运行速度有了明显地提高!下面我将从这三个方面分别进行总结

SQL Sever数据库中巧妙地建立索引能起到事半功倍的效果,笔者在工作实践中发现,不良的SQL往往来自于不恰当的索引设计、不充份的连接条件和不可优化的where子句。在对它们进行适当的优化后,其运行速度有了明显地提高!下面我将从这三个方面分别进行总结: 

为了更直观地说明问题,所有实例中的SQL运行时间均经过测试,不超过1秒的均表示为(

测试环境 

主机:HP LH II 

主频:330MHZ 

内存:128兆 

操作系统:Operserver5.0.4 

数据库:Sybase11.0.3 

一、不合理的索引设计 

例:表record有620000行,试看在不同的索引下,下面几个SQL的运行情况: 

1.在date上建有一个非群集索引

<ol>
<li><span><span>select count(*) from record where date </span><span>></span><span>'19991201' and date </span><span><span> '19991214'and amount </span><span>></span><span>2000 (25秒)   </span></span></span></li>
<li><span>select date,sum(amount) from record group by date(55秒)   </span></li>
<li>
<span>select count(*) from record where date </span><span>></span><span>'19990901' and place in ('BJ','SH') (27秒)  </span>
</li>
</ol>

分析: 
date上有大量的重复值,在非群集索引下,数据在物理上随机存放在数据页上,在范围查找时,必须执行一次表扫描才能找到这一范围内的全部行。 

2.在date上的一个群集索引

<ol>
<li><span><span>select count(*) from record where date </span><span>></span><span>'19991201' and date </span><span><span> '19991214' and amount </span><span>></span><span>2000(14秒)   </span></span></span></li>
<li><span>select date,sum(amount) from record group by date(28秒)   </span></li>
<li>
<span>select count(*) from record where date </span><span>></span><span>'19990901' and place in ('BJ','SH')(14秒) </span>
</li>
</ol>

分析: 
在群集索引下,数据在物理上按顺序在数据页上,重复值也排列在一起,因而在范围查找时,可以先找到这个范围的起末点,且只在这个范围内扫描数据页,避免了大范围扫描,提高了查询速度。 

3.在place,date,amount上的组合索引

<ol>
<li><span><span>select count(*) from record where date </span><span>></span><span>'19991201' and date </span><span><span> '19991214' and amount </span><span>></span><span>2000(26秒)   </span></span></span></li>
<li><span>select date,sum(amount) from record group by date(27秒)   </span></li>
<li>
<span>select count(*) from record where date </span><span>></span><span>'19990901' and place in ('BJ, 'SH')(</span><span><span> </span><span>1</span><span>秒) </span></span>
</li>
</ol>

分析: 
这是一个不很合理的组合索引,因为它的前导列是place,第一和第二条SQL没有引用place,因此也没有利用上索引;第三个SQL使用了place,且引用的所有列都包含在组合索引中,形成了索引覆盖,所以它的速度是非常快的。 

4.在date,place,amount上的组合索引 

<ol>
<li><span><span>select count(*) from record where date </span><span>></span><span>'19991201' and date </span><span><span> '19991214' and amount </span><span>></span><span>2000(</span><span><span> </span><span>1</span><span>秒)   </span></span></span></span></li>
<li><span>select date,sum(amount) from record group by date(11秒)   </span></li>
<li>
<span>select count(*) from record where date </span><span>></span><span>'19990901' and place in ('BJ','SH')(</span><span><span> </span><span>1</span><span>秒)  </span></span>
</li>
</ol>

分析: 
这是一个合理的组合索引。它将date作为前导列,使每个SQL都可以利用索引,并且在第一和第三个SQL中形成了索引覆盖,因而性能达到了最优。 

5.总结: 

缺省情况下建立的索引是非群集索引,但有时它并不是最佳的;合理的索引设计要建立在对各种查询的分析和预测 上。一般来说: 

①.有大量重复值、且经常有范围查询 

(between, >,=, ②.经常同时存取多列,且每列都含有重复值可考虑建立组合索引; 
③.组合索引要尽量使关键查询形成索引覆盖,其前导列一定是使用最频繁的列。 

二、不充份的连接条件:

例:表card有7896行,在card_no上有一个非聚集索引,表account有191122行,在 account_no上有一个非聚集索引,试看在不同的表连接条件下,两个SQL的执行情况: 

<ol><li><span><span>select sum(a.amount) from account a,card b where </span><span>a.card_no</span><span> = </span><span>b</span><span>.card_no(20秒)  </span></span></li></ol>

将SQL改为: 

<ol><li><span><span>select sum(a.amount) from account a,card b where </span><span>a.card_no</span><span> = </span><span>b</span><span>.card_no and </span><span>a.account_no</span><span>=</span><span>b</span><span>.account_no(</span><span><span> </span><span>1</span><span>秒)  </span></span></span></li></ol>

分析: 
在第一个连接条件下,最佳查询方案是将account作外层表,card作内层表,利用card上的索引,其I/O次数可由以下公式估算为: 

外层表account上的22541页+(外层表account的191122行*内层表card上对应外层表第一行所要查找的3页)=595907次I/O 

在第二个连接条件下,最佳查询方案是将card作外层表,account作内层表,利用account上的索引,其I/O次数可由以下公式估算为: 

外层表card上的1944页+(外层表card的7896行*内层表account上对应外层表每一行所要查找的4页)= 33528次I/O 

可见,只有充份的连接条件,真正的最佳方案才会被执行。 

总结: 

1.多表操作在被实际执行前,查询优化器会根据连接条件,列出几组可能的连接方案并从中找出系统开销最小的最佳方案。连接条件要充份考虑带有索引的表、行数多的表;内外表的选择可由公式:外层表中的匹配行数*内层表中每一次查找的次数确定,乘积最小为最佳方案。 

2.查看执行方案的方法 用set showplanon,打开showplan选项,就可以看到连接顺序、使用何种索引的信息;想看更详细的信息,需用sa角色执行dbcc(3604,310,302)。 

三、不可优化的where子句

1.例:下列SQL条件语句中的列都建有恰当的索引,但执行速度却非常慢: 

<ol>
<li><span><span>select * from record where substring(card_no,1,4)='5378'(13秒)   </span></span></li>
<li>
<span>select * from record where amount/30</span><span><span> </span><span>1000</span><span>(11秒)   </span></span>
</li>
<li><span>select * from record where convert(char(10),date,112)='19991201'(10秒)  </span></li>
</ol>

分析: 
where子句中对列的任何操作结果都是在SQL运行时逐列计算得到的,因此它不得不进行表搜索,而没有使用该列上面的索引;如果这些结果在查询编译时就能得到,那么就可以被SQL优化器优化,使用索引,避免表搜索,因此将SQL重写成 下面这样: 

<ol>
<li><span><span>select * from record where card_no like '5378%'(</span><span><span> </span><span>1</span><span>秒)   </span></span></span></li>
<li>
<span>select * from record where amount </span><span><span> </span><span>1000</span><span>*30(</span><span><span> </span><span>1</span><span>秒)   </span></span></span>
</li>
<li>
<span>select * from record where </span><span>date</span><span>= </span><span>'1999/12/01'</span><span> (</span><span><span> </span><span>1</span><span>秒)  </span></span>
</li>
</ol>

你会发现SQL明显快起来! 

2.例:表stuff有200000行,id_no上有非群集索引,请看下面这个SQL: 

<ol><li><span><span>select count(*) from stuff where id_no in('0','1')(23秒)  </span></span></li></ol>

分析: 
where条件中的'in'在逻辑上相当于'or',所以语法分析器会将in ('0','1')转化为id_no ='0' or id_no='1'来执行。我们期望它会根据每个or子句分别查找,再将结果相加,这样可以利用id_no上的索引;但实际上(根据showplan),它却采用了"OR策略",即先取出满足每个or子句的行,存入临时数据库的工作表中,再建立唯一索引以去掉重复行,最后从这个临时表中计算结果。因此,实际过程没有利用id_no上索引,并且完成时间还要受tempdb数据库性能的影响。 

实践证明,表的行数越多,工作表的性能就越差,当stuff有620000行时,执行时间竟达到220秒!还不如将or子句分 
开: 

<ol>
<li><span><span>select count(*) from stuff where </span><span>id_no</span><span>=</span><span>'0'</span><span>   </span></span></li>
<li>
<span>select count(*) from stuff where </span><span>id_no</span><span>=</span><span>'1'</span><span>  </span>
</li>
</ol>

得到两个结果,再作一次加法合算。因为每句都使用了索引,执行时间只有3秒,在620000行下,时间也只有4秒。或者,用更好的方法,写一个简单的存储过程: 

<ol>
<li><span><span>create proc count_stuff as   </span></span></li>
<li><span>declare @a int   </span></li>
<li><span>declare @b int   </span></li>
<li><span>declare @c int   </span></li>
<li><span>declare @d char(10)   </span></li>
<li><span>begin   </span></li>
<li>
<span>select @</span><span>a</span><span>=</span><span>count</span><span>(*) from stuff where </span><span>id_no</span><span>=</span><span>'0'</span><span>   </span>
</li>
<li>
<span>select @</span><span>b</span><span>=</span><span>count</span><span>(*) from stuff where </span><span>id_no</span><span>=</span><span>'1'</span><span>   </span>
</li>
<li><span>end   </span></li>
<li>
<span>select @</span><span>c</span><span>=@a+@b   </span>
</li>
<li>
<span>select @</span><span>d</span><span>=</span><span>convert</span><span>(char(10),@c)   </span>
</li>
<li><span>print @d </span></li>
</ol>

直接算出结果,执行时间同上面一样快! 

总结: 可见,所谓优化即where子句利用了索引,不可优化即发生了表扫描或额外开销。 

1.任何对列的操作都将导致表扫描,它包括数据库函数、计算表达式等等,查询时要尽可能将操作移至等号右边。 

2.in、or子句常会使用工作表,使索引失效;如果不产生大量重复值,可以考虑把子句拆开;拆开的子句中应该包含索引。 

3.要善于使用存储过程,它使SQL变得更加灵活和高效。 从以上这些例子可以看出,SQL优化的实质就是在结果正确的前提下,用优化器可以识别的语句,充份利用索引,减少表扫描的I/O次数,尽量避免表搜索的发生。其实SQL的性能优化是一个复杂的过程,上述这些只是在应用层次的一种体现,深入研究还会涉及数据库层的资源配置、网络层的流量控制以及操作系统层的总体设计。 

关于SQL Server数据库科学建立索引的知识就介绍到这里了,希望本次的介绍能够对您有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment