Home Database SQL How to optimize SQL queries? (detailed explanation)

How to optimize SQL queries? (detailed explanation)

Nov 30, 2019 pm 05:54 PM
sql query

How to optimize SQL queries? (detailed explanation)

Why should we optimize

The throughput bottleneck of the system often appears in the access speed of the database, that is, as the As the application runs, there will be more and more data in the database, and the processing time will slow down accordingly. Moreover, the data is stored on the disk, and the read and write speed cannot be compared with that of the memory.

How Optimization

1. When designing the database: design of database tables and fields, storage engine

2. Make good use of the functions provided by MySQL itself, such as indexes and optimization of statement writing

3. MySQL cluster, sub-database and sub-table, read-write separation

The Internet has a lot of experience in optimizing SQL statements, so this article puts aside these and tries to optimize the DAO layer. and database design optimization, and list two simple examples

Example 1:ERPQuery optimization

Current situation analysis:

1. Lack of associated indexes
2. Mysql itself has limited performance and does not support the association of multiple tables. The current performance is mainly focused on list queries, which are associated with many tables

Countermeasures:

1 Add necessary indexes: View the execution records through explain, and add indexes according to the execution plan;
2 First count the primary keys of the main table of business data, obtain a smaller result set, and then Then use the result set association query;
1) First query and display the primary key of the business data based on the main table and conditions
2) Use the primary key as the query condition, and then associate other related tables to query the required business fields
3 ) When querying the main table, for query conditions that need to be associated with other tables, you need to set up table association only when this condition is set

例如 有如下表 TT_A   TT_B    TT_C  TT_D

假设未优化前的SQL是这样的

SELECT
    A.ID,
    ....
    B.NAME,
    .....
    C.AGE,
    ....
    D.SEX
    .....

FROM  TT_A A
LEFT JOIN TT_B B ON A.ID  = B.ITEM_ID
LEFT JOIN TT_C C ON B.ID = C.ITEM_ID
LEFT JOIN TT_D D ON C.ID = D.ITEM_ID
WHERE 1=1AND A.XX = ?AND A.VV = ?.....

那么优化后的SQL是

第一步

SELECT
    A.ID

FROM  TT_A A
WHERE 1=1AND A.XX = ?AND A.VV = ?第二步

SELECT
    A.ID,
    ....
    B.NAME,
    .....
    C.AGE,
    ....
    D.SEX
    .....
FROM  ( SELECT A.ID,..... FROM  TT_A  WHERE ID IN (1,2,3..)  ) A
LEFT JOIN TT_B B ON A.ID  = B.ITEM_ID
LEFT JOIN TT_C C ON B.ID = C.ITEM_ID
LEFT JOIN TT_D D ON C.ID = D.ITEM_ID
WHERE 1=1AND A.XX = ?AND A.VV = ?
Copy after login

Summary:

This kind of optimization is suitable for list queries, because the conditions of a list query are generally linked to the main table, so use this to establish key field indexes, and at the same time greatly reduce the main table through the restriction of query conditions. amount of data. In this way, it will be much faster when correlating other tables.

Example 2: Article search optimization

Suppose you want to create an article search function for Tieba. The simplest and most direct way is The storage structure is to use a relational database to create such a relational database table TT_ARTICLES for storing articles:

Then, if the current search keyword is "target", we can Use string matching to perform matching queries on the CONTENT column:

select * from ARTICLES where CONTENT like '% 目标 %';
Copy after login

This easily implements the search function. However, this approach has obvious problems, that is, using % for string matching is very inefficient, so such a query needs to traverse the entire table (full table scan). When there are a few or dozens of articles, this is not a problem, but if there are hundreds of thousands or millions of articles, this method is completely unfeasible. Not to mention that a single relational database table cannot accommodate such large data. Even if it can accommodate it, it needs to be scanned again. The time cost here is unimaginable

So, we have to introduce "inversion" "indexing" technology. In the scenario described above, we can split this concept into two parts to explain: Okay, the ARTICLES table above still exists, but now a keyword table KEYWORDS needs to be added, and the KEYWORD column needs to be indexed. Therefore, the record of this keyword can be quickly found:

Of course, we also need a relationship table to combine the KEYWORDS table and the ARTICLES table, KEYWORD_ID and ARTICLE_ID as unions Primary key

#You see, this is actually a many-to-many relationship, that is, the same keyword can appear in multiple articles, and one article can contain multiple different keywords. In this way, we can first find the corresponding KEYWORD_ID from the KEYWARDS table based on the indexed keywords, then find the ARTICLE_ID based on its association table above, and then use it to find the corresponding article in the ARTICLES table.

Summary:

This seems to be three searches, but because the index is used each time, a full table scan is eliminated. When the amount of data is small, The speed is not slow, and when implemented using SQL, this process can be completely put into a SQL statement. When the amount of data is small, the above method is good enough. This solves the performance problems caused by full table scans and string % match queries.

Summary:

During the technical interview, if you can give practical examples, or directly talk about the problems and gains in your development process, the interview branch will be Add a lot, and your answers should be more logical. Don't go here and there, which can easily confuse yourself. For example, when asked about how to optimize SQL, you should not directly answer adding indexes. You can answer like this:

Hello interviewer, first of all, our project DB data volume has encountered a bottleneck, resulting in list query being very slow and giving users a poor experience. In order to solve this problem, there are many methods, such as the most basic database table design, Basic SQL optimization, MYSQL clustering, read-write separation, sub-database and sub-table, adding a cache layer to the architecture, etc. Their advantages and disadvantages... We combine these and then combine them with the characteristics of our project. Finally, we choose when selecting technology. Who.

If you answer the questions in such an orderly and well-reasoned way and also talk about so many knowledge points outside the questions, the interviewer will think that you are not just a person who can write code, but that you have clear logic. You have your own understanding and thinking about technology selection

This article comes from the SQL Tutorial column, welcome to learn!

The above is the detailed content of How to optimize SQL queries? (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

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)

Meituan interview question: Have you ever encountered slow SQL? How was it solved? Meituan interview question: Have you ever encountered slow SQL? How was it solved? Aug 24, 2023 pm 03:41 PM

MySQL's slow query log is a log record provided by MySQL. It is used to record statements in MySQL whose query time exceeds (greater than) the set threshold (long_query_time) and records them in the slow query log.

PHP and PDO: How to execute complex SQL queries PHP and PDO: How to execute complex SQL queries Jul 28, 2023 pm 03:43 PM

PHP and PDO: How to execute complex SQL query statements When processing database operations, PHP provides a powerful extension library PDO (PHPDataObjects) to simplify interaction with the database. PDO supports a variety of databases, such as MySQL, SQLite, etc., and also provides a wealth of functions and methods to facilitate developers to perform various database operations. This article will introduce how to use PDO to execute complex SQL query statements, and attach corresponding code examples. Connect to the database

What are the common table operations in PHP programming? What are the common table operations in PHP programming? Jun 12, 2023 am 09:46 AM

In web development, tables are the most basic and commonly used elements, and PHP is a popular server-side programming language. There are many common techniques and methods in table operations. This article will introduce common table operations in PHP programming. Displaying data tables In PHP, you can use the table tag in HTML to display data tables. It is worth noting that the table must be generated in a PHP script. Here is an example of a basic HTML table tag: <table><tr>

PHP query statement usage example PHP query statement usage example Mar 23, 2024 am 11:27 AM

PHP is a powerful server-side scripting language that is widely used in web development. In web development, we often need to interact with the database and execute query statements to obtain data. This article will introduce you to how to write query statements and usage examples in PHP. 1. Connect to the database Before using PHP to query the database, you first need to establish a connection with the database. Generally, we will use the MySQL database as an example. The code to connect to the database is as follows: $servername=

Why does my Go program error when executing SQL queries? Why does my Go program error when executing SQL queries? Jun 09, 2023 pm 06:10 PM

In Go programming, using SQL queries is a common task. However, sometimes errors occur when executing SQL queries, causing the program to fail to execute correctly. In order to solve these errors, we need to have a deep understanding of how SQL queries and the Go language interact. Below are some possible errors and corresponding solutions. Lack of database driver In Go language, you need to use a specific database driver to connect and operate the database. If you try to perform a database query and the database driver is not properly installed and configured

How to optimize SQL query statements and index usage in PHP development? How to optimize SQL query statements and index usage in PHP development? Nov 02, 2023 pm 12:12 PM

How to optimize SQL query statements and index usage in PHP development? In PHP development, database query is a very common operation. However, when the amount of data increases, query performance may be affected, causing the application to slow down. In order to improve query performance, we need to optimize the use of SQL query statements and indexes. This article will introduce some optimization tips and best practices to help you improve SQL query performance in PHP development. 1. Use the correct index: Index is an important part of the database to improve query performance. in design data

Most SQL query efficiency optimization practices in PHP programming Most SQL query efficiency optimization practices in PHP programming Jun 23, 2023 am 10:37 AM

With the development of network technology, PHP programming has become the mainstream of website development for many companies. In PHP programming, SQL query efficiency is an issue that requires every programmer to pay attention and deal with. Inefficient SQL query will lead to slow website response, high system load or other unfriendly effects. Therefore, this article will focus on introducing various SQL query efficiency optimization practices in PHP programming to improve the execution efficiency of the program and the response speed of the entire system. Database index Database index is a basic method to improve the speed of database query

How to query and filter data in MySQL using SQL statements? How to query and filter data in MySQL using SQL statements? Dec 17, 2023 pm 05:13 PM

How to query and filter data in MySQL using SQL statements? MySQL is a commonly used relational database management system. It provides a powerful SQL query language that can help us easily query and filter data. This article will introduce how to use SQL statements to query and filter data in MySQL, including using the SELECT statement for simple queries, using the WHERE clause for conditional filtering, using the ORDERBY clause for sorting, and using LIMIT

See all articles