Home Database Mysql Tutorial 8 common SQL usage errors in Mysql

8 common SQL usage errors in Mysql

Aug 27, 2019 am 10:49 AM
mysql

Preface

MySQL continued to maintain a strong growth trend in database popularity in 2016. More and more customers are building their applications on the MySQL database, or even migrating from Oracle to MySQL. However, some customers also encounter problems such as slow response time and full CPU usage when using the MySQL database.

Alibaba Cloud RDS expert service team has helped cloud customers solve many emergency problems. Some common SQL problems that appear in the "ApsaraDB Expert Diagnostic Report" are summarized as follows for your reference.

1. LIMIT statement

Paging query is one of the most commonly used scenarios, but it is also usually the most prone to problems.

For example, for the following simple statement, the general DBA's idea is to add a combined index on the type, name, and create_time fields. In this way, conditional sorting can effectively utilize the index, and the performance can be improved rapidly.

SELECT *  FROM   operation  WHERE  type = 'SQLStats'         AND name = 'SlowLog'  ORDER  BY create_time  LIMIT  1000, 10;
Copy after login

Well, maybe more than 90% of DBAs solve this problem and stop there.

But when the LIMIT clause becomes "LIMIT 1000000,10", programmers will still complain: Why is it still slow if I only fetch 10 records?

You must know that the database does not know where the 1,000,000th record begins. Even if there is an index, it needs to be calculated from the beginning. When this kind of performance problem occurs, in most cases the programmer is lazy. In scenarios such as front-end data browsing and page turning, or big data export in batches, the maximum value of the previous page can be used as a parameter as a query condition. SQL is redesigned as follows:

SELECT   *  FROM     operation  WHERE    type = 'SQLStats'  AND      name = 'SlowLog'  AND      create_time > '2017-03-16 14:00:00'  ORDER BY create_time limit 10;
Copy after login

2. Implicit conversion

The mismatch between query variable and field definition types in SQL statements is another common error. For example, the following statement:

8 common SQL usage errors in Mysql

The field bpn is defined as varchar(20). MySQL's strategy is to convert the string into a number before comparing. The function acts on table fields and the index becomes invalid.

The above situation may be the parameters automatically filled in by the application framework, rather than the programmer's original intention. Nowadays, there are many application frameworks that are very complicated. While they are easy to use, be careful that they may dig holes for you.

3. Association update and deletion

Although MySQL5.6 introduces the materialization feature, special attention should be paid to the fact that it is currently only optimized for query statements. For updates or deletions, you need to manually rewrite it as JOIN.

For example, in the UPDATE statement below, MySQL actually executes a loop/nested subquery (DEPENDENT SUBQUERY), and its execution time can be imagined.

8 common SQL usage errors in Mysql

Execution plan:

8 common SQL usage errors in Mysql

4. Mixed sort

MySQL Indexes cannot be used for mixed sorting. But in some scenarios, there are still opportunities to use special methods to improve performance.

8 common SQL usage errors in Mysql

The execution plan is displayed as a full table scan:

8 common SQL usage errors in Mysql

Since is_reply only has two states: 0 and 1, we follow After the following method was rewritten, the execution time was reduced from 1.58 seconds to 2 milliseconds.

8 common SQL usage errors in Mysql

5、EXISTS语句

MySQL 对待 EXISTS 子句时,仍然采用嵌套子查询的执行方式。如下面的 SQL 语句:

8 common SQL usage errors in Mysql

执行计划为:

8 common SQL usage errors in Mysql

去掉 exists 更改为 join,能够避免嵌套子查询,将执行时间从1.93秒降低为1毫秒。

8 common SQL usage errors in Mysql

新的执行计划:

8 common SQL usage errors in Mysql

6、条件下推

外部查询条件不能够下推到复杂的视图或子查询的情况有:

聚合子查询;

含有 LIMIT 的子查询;

UNION 或 UNION ALL 子查询;

输出字段中的子查询;

如下面的语句,从执行计划可以看出其条件作用于聚合子查询之后:

8 common SQL usage errors in Mysql

8 common SQL usage errors in Mysql

确定从语义上查询条件可以直接下推后,重写如下:

SELECT target Count(*)  FROM   operation  WHERE  target = 'rm-xxxx'  GROUP  BY target
Copy after login

执行计划变为:

8 common SQL usage errors in Mysql

关于 MySQL 外部条件不能下推的详细解释说明请参考文章:

http://mysql.taobao.org/monthly/2016/07/08

相了解更多相关问题请访问PHP中文网:mysql视频教程

The above is the detailed content of 8 common SQL usage errors in Mysql. 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)

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

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.

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 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