Home Database Mysql Tutorial MySQL 怎么使用索引 较为详细的分析和例子

MySQL 怎么使用索引 较为详细的分析和例子

Jun 07, 2016 pm 04:25 PM
mysql use example analyze how index

MySQL 如何使用索引 较为详细的分析和例子 在数据库表中,使用索引可以大大提高查询速度。 假如我们创建了一个 testIndex 表: CREATE TABLE testIndex(i_testID INT NOT NULL,vc_Name VARCHAR(16) NOTNULL); 我们随机向里面插入了 1000 条记录,其中有一条 i

MySQL 如何使用索引 较为详细的分析和例子

在数据库表中,使用索引可以大大提高查询速度。  假如我们创建了一个 testIndex 表:

  CREATE TABLE testIndex(i_testID INT NOT NULL,vc_Name VARCHAR(16) NOTNULL);

  我们随机向里面插入了 1000 条记录,其中有一条 i_testID vc_Name 555 erquan

  在查找 vc_Name="erquan" 的记录 SELECT *FROM testIndex WHERE vc_Name='erquan'; 时,如果在vc_Name 上已经建立了索引,MySql 无须任何扫描,即准确可找到该记录!相反,MySql 会扫描所有记录,即要查询 1000。以索引将查询速度提高 100 倍。

  一、索引分单列索引和组合索引

  单列索引:即一个索引只包含单个列,一个表可以有多个单列索引,但这不是组合索引。组合索引:即一个索包含多个列。

  二、介绍一下索引的类型

  1、普通索引。

  这是最基本的索引,它没有任何限制。它有以下几种创建方式:

  (1)创建索引:CREATE INDEX indexName ONtableName(tableColumns(length));如果是CHAR,VARCHAR类型,length可以小于字段实际长度;如果是 BLOB 和 TEXT 类型,必须指定 length,下同。

  (2)修改表结构:ALTER tableName ADD INDEX[indexName] ON (tableColumns(length))

  (3)创建表的时候直接指定:CREATE TABLE tableName ( [...],INDEX [indexName] (tableColumns(length)) ;

  2、唯一索引。

  它与前面的"普通索引"类似,不同的就是:索引列的值必须唯一,但允许有空值。如果是组合索引,则列值的组合必须唯一。它有以下几种创建方式:

  (1)创建索引:CREATE UNIQUE INDEX indexName ONtableName(tableColumns(length))

  (2)修改表结构:ALTER tableName ADD UNIQUE[indexName] ON (tableColumns(length))

  (3)创建表的时候直接指定:CREATE TABLE tableName ( [...],UNIQUE [indexName] (tableColumns(length));

  3、主键索引

  它是一种特殊的唯一索引,不允许有空值。一般是在建表的时候同时创建主键索引:CREATE TABLE testIndex(i_testID INT NOT NULL AUTO_INCREMENT,vc_NameVARCHAR(16) NOT NULL,PRIMARY KEY(i_testID)); 当然也可以用ALTER 命令。记住:一个表只能有一个主键。

  4、全文索引

  MySQL 从 3.23.23 版开始支持全文索引和全文检索。

  删除索引的语法:DROP INDEX index_name ON tableName

  三、单列索引和组合索引

  为了形象地对比两者,再建一个表:

  CREATE TABLE myIndex ( i_testID INT NOT NULL AUTO_INCREMENT, vc_NameVARCHAR(50) NOT NULL, vc_City VARCHAR(50) NOT NULL, i_Age INT NOT NULL,i_SchoolID INT NOT NULL, PRIMARY KEY (i_testID) );

  在这 10000 条记录里面 7 上 8 下地分布了 5 条 vc_Name="erquan" 的记录,只不过 city,age,school 的组合各不相同。

  来看这条 T-SQL:SELECT i_testID FROM myIndex WHEREvc_Name='erquan' AND vc_City='郑州' AND i_Age=25;

  首先考虑建单列索引:

  在 vc_Name 列上建立了索引。执行 T-SQL 时,MYSQL 很快将目标锁定在了 vc_Name=erquan 的 5 条记录上,取出来放到一中间结果集。在这个结果集里,先排除掉 vc_City 不等于"郑州"的记录,再排除 i_Age 不等于 25 的记录,最后筛选出唯一的符合条件的记录。

  虽然在 vc_Name 上建立了索引,查询时MYSQL不用扫描整张表,效率有所提高,但离我们的要求还有一定的距离。同样的,在 vc_City 和 i_Age 分别建立的单列索引的效率相似。

  为了进一步榨取 MySQL 的效率,就要考虑建立组合索引。就是将 vc_Name,vc_City,i_Age 建到一个索引里:

  ALTER TABLE myIndex ADD INDEX name_city_age(vc_Name(10),vc_City,i_Age);

  建表时,vc_Name 长度为 50,这里为什么用 10 呢?因为一般情况下名字的长度不会超过 10,这样会加速索引查询速度,还会减少索引文件的大小,提高 INSERT 的更新速度。

  执行 T-SQL 时,MySQL 无须扫描任何记录就到找到唯一的记录!!

  肯定有人要问了,如果分别在 vc_Name,vc_City,i_Age 上建立单列索引,让该表有 3 个单列索引,查询时和上述的组合索引效率一样吗?大不一样,远远低于我们的组合索引。虽然此时有了三个索引,但 MySQL 只能用到其中的那个它认为似乎是最有效率的单列索引。

  建立这样的组合索引,其实是相当于分别建立了

  vc_Name,vc_City,i_Age
  vc_Name,vc_City
  vc_Name

  这样的三个组合索引!为什么没有 vc_City,i_Age 等这样的组合索引呢?这是因为 mysql 组合索引“最左前缀”的结果。简单的理解就是只从最左面的开始组合。并不是只要包含这三列的查询都会用到该组合索引,下面的几个 T-SQL 会用到:

  SELECT * FROM myIndex WHREE vc_Name="erquan" ANDvc_City="郑州"
  SELECT * FROM myIndex WHREEvc_Name="erquan"

  而下面几个则不会用到:

  SELECT * FROM myIndex WHREE i_Age=20 AND vc_City="郑州"
  SELECT * FROM myIndex WHREE vc_City="郑州"

  四、使用索引

  到此你应该会建立、使用索引了吧?但什么情况下需要建立索引呢?一般来说,在 WHERE 和 JOIN 中出现的列需要建立索引,但也不完全如此,因为 MySQL 只对 ,>=,BETWEEN,IN,以及某些时候的LIKE(后面有说明)才会使用索引。

  SELECT t.vc_Name FROM testIndex t LEFT JOIN myIndex m ONt.vc_Name=m.vc_Name WHERE m.i_Age=20 AND m.vc_City='郑州'时,有对 myIndex 表的 vc_City 和 i_Age 建立索引的需要,由于testIndex 表的 vc_Name 开出现在了 JOIN 子句中,也有对它建立索引的必要。

  刚才提到了,只有某些时候的 LIKE 才需建立索引?是的。因为在以通配符 % 和 _ 开头作查询时,MySQL 不会使用索引,如 SELECT * FROM myIndex WHERE vc_Name like'erquan%'
会使用索引,而 SELECT * FROM myIndex WHEREt vc_Namelike'%erquan' 就不会使用索引了。

  五、索引的不足之处

  上面说了那么多索引的好话,它真的有像传说中那么优秀么?当然会有缺点了。

  1、虽然索引大大提高了查询速度,同时却会降低更新表的速度,如对表进行 INSERT、UPDATE 和DELETE。因为更新表时,MySQL 不仅要保存数据,还要保存一下索引文件。

  2、建立索引会占用磁盘空间的索引文件。一般情况这个问题不太严重,但如果你在一个大表上创建了多种组合索引,索引文件的会膨胀很快。


  讲了这么多,无非是想利用索引提高数据库的执行效率。不过索引只是提高效率的一个因素。如果你的MySQL 有大数据的表,就需要花时间研究建立最优秀的索引或优化查询语句。
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles