search
HomeDatabaseMysql TutorialShare a MySQL multi-column index optimization example code

As the data captured by crawlers continues to increase, the database and query statements have been continuously optimized in the past two days. One of the table structures is as follows:

CREATE TABLE `newspaper_article` (
  `id` varchar(50) NOT NULL COMMENT '编号',
  `title` varchar(190) NOT NULL COMMENT '标题',
  `author` varchar(255) DEFAULT NULL COMMENT '作者',
  `date` date NULL DEFAULT NULL COMMENT '发表时间',
  `content` longtext COMMENT '正文',
  `status` tinyint(4) DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `idx_status_date` (`status`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='文章表';

According to business needs, the idx_status_date index has been added, which is particularly time-consuming when executing the following SQL:

SELECT id, title, status, date FROM article WHERE status > -2 AND date = '2016-01-07';

According to observations, the number of new data added every day is approximately within 2,500. I thought that a specific date was specified here '2016-01-07', and the actual amount of data that needs to be scanned should be within 2500, but this is not the case:
Share a MySQL multi-column index optimization example code
A total of 185,589 pieces of data were actually scanned, which was much higher than the estimated 2,500 pieces, and the actual execution time was nearly 3 seconds:

Share a MySQL multi-column index optimization example code

Why is this?

Solution

After changing idx_status_date (status, date) to idx_status (status), check the MySQL execution plan:

Share a MySQL multi-column index optimization example code

You can see that after changing the multi-column index to a single-column index, there is no change in the total amount of data to be scanned in the execution plan. Combined with the fact that multi-column indexes follow the leftmost prefix principle, it is speculated that the above query statement only uses the index of the leftmost status of idx_status_date.

I flipped through "High Performance MySQL" and found the following passage, which confirmed my idea:

If there is a range query for a certain column in the query, then the right side of All columns cannot be looked up using index optimization. For example, there is a query WHERE last_name = 'Smith' AND first_name LIKE 'J%' AND dob = '1976-12-23'. This query can only use the first two columns of the index, because here LIKE is a range condition (but the server can use the remaining columns for other purposes). If the number of range query column values ​​is limited, you can replace the range condition by using multiple equal conditions.

Therefore, there are two solutions here:

  • You can replace the range condition by using multiple equal conditions

  • Modify idx_status_date (status, date) to index idx_date_status (date, status) and create a new idx_status index to achieve the same effect.

Optimized execution plan:

Share a MySQL multi-column index optimization example code

##Actual execution result:

Share a MySQL multi-column index optimization example code

Summary

When people talk about indexes, if they don’t specify the type, they are probably talking about

B-Tree indexes. It uses B-Tree data structure to store data. We use the term "B-Tree" because MySQL also uses this keyword in CREATE TABLE and other statements. However, the underlying storage engine may also use different storage structures. InnoDB uses B+Tree. Suppose there is the following data table:

CREATE TABLE People (
  last_name  varchar(50)    not null,
  first_name varchar(50)    not null,
  dob        date           not null,
  gender     enum('m', 'f') not null,
  key(last_name, first_name, dob)
);

B-Tree index is valid for the following types of queries

  • Full value matching

    Full value matching refers to Match all columns in the index. For example, the index in the above table can be used to find people named Cuba Allen and born on 1960-01-01.

  • Match the leftmost prefix

    The index in the above table can be used to find all people with the last name of Allen, that is, only the first column of the index is used.

  • Match column prefix

    Only matches the beginning of the value of a column. For example, the index in the above table can be used to find all people whose last names begin with J. Only the first column of the index is used here.

  • Matching range values

    For example, the index in the above table can be used to find people with last names between Allen and Barrymore. Only the first column of the index is used here.

  • Exactly match a certain column and range match another column

    The index in the above table can also be used to find all people whose last name is Allen and whose first name starts with the letter K (such as Kim, Karl, etc.) people. That is, the first column last_name matches completely, and the second column first_name matches the range.

  • Query that only accesses the index

    B-Tree can usually support "query that only accesses the index", that is, the query only needs to access the index without accessing the data rows.

Some limitations of B-Tree index

  • If you do not start searching according to the leftmost column of the index, you cannot use the index. For example, the index in the above table cannot be used to find people named Bill, nor can it be used to find people with a specific birthday, because neither column is the leftmost data column. Similarly, there is no way to find people whose last names end with a certain letter.

  • Columns in the index cannot be skipped. That is, the index on the table above cannot be used to find people with the last name Smith who were born on a specific date. If you do not specify a name (first_name), MySQL can only use the first column of the index.

  • If there is a range query for a certain column in the query, all columns to the right of it cannot be searched using index optimization. For example, there is a query WHERE last_name = 'Smith' AND first_name LIKE 'J%' AND dob = '1976-12-23'. This query can only use the first two columns of the index, because here LIKE is a range condition (but the server can use the remaining columns for other purposes). If the number of range query column values ​​is limited, you can replace the range condition by using multiple equal conditions.


The above is the detailed content of Share a MySQL multi-column index optimization example code. For more information, please follow other related articles on the PHP Chinese website!

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools