search
HomeDatabaseMysql Tutorial8 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;

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;

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

执行计划变为:

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
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How does MySQL handle data replication?How does MySQL handle data replication?Apr 28, 2025 am 12:25 AM

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

How can you use the EXPLAIN statement to analyze query performance?How can you use the EXPLAIN statement to analyze query performance?Apr 28, 2025 am 12:24 AM

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

How do you back up and restore a MySQL database?How do you back up and restore a MySQL database?Apr 28, 2025 am 12:23 AM

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

What are some common causes of slow queries in MySQL?What are some common causes of slow queries in MySQL?Apr 28, 2025 am 12:18 AM

The main reasons for slow MySQL query include missing or improper use of indexes, query complexity, excessive data volume and insufficient hardware resources. Optimization suggestions include: 1. Create appropriate indexes; 2. Optimize query statements; 3. Use table partitioning technology; 4. Appropriately upgrade hardware.

What are views in MySQL?What are views in MySQL?Apr 28, 2025 am 12:04 AM

MySQL view is a virtual table based on SQL query results and does not store data. 1) Views simplify complex queries, 2) Enhance data security, and 3) Maintain data consistency. Views are stored queries in databases that can be used like tables, but data is generated dynamically.

What are the differences in syntax between MySQL and other SQL dialects?What are the differences in syntax between MySQL and other SQL dialects?Apr 27, 2025 am 12:26 AM

MySQLdiffersfromotherSQLdialectsinsyntaxforLIMIT,auto-increment,stringcomparison,subqueries,andperformanceanalysis.1)MySQLusesLIMIT,whileSQLServerusesTOPandOracleusesROWNUM.2)MySQL'sAUTO_INCREMENTcontrastswithPostgreSQL'sSERIALandOracle'ssequenceandt

What is MySQL partitioning?What is MySQL partitioning?Apr 27, 2025 am 12:23 AM

MySQL partitioning improves performance and simplifies maintenance. 1) Divide large tables into small pieces by specific criteria (such as date ranges), 2) physically divide data into independent files, 3) MySQL can focus on related partitions when querying, 4) Query optimizer can skip unrelated partitions, 5) Choosing the right partition strategy and maintaining it regularly is key.

How do you grant and revoke privileges in MySQL?How do you grant and revoke privileges in MySQL?Apr 27, 2025 am 12:21 AM

How to grant and revoke permissions in MySQL? 1. Use the GRANT statement to grant permissions, such as GRANTALLPRIVILEGESONdatabase_name.TO'username'@'host'; 2. Use the REVOKE statement to revoke permissions, such as REVOKEALLPRIVILEGESONdatabase_name.FROM'username'@'host' to ensure timely communication of permission changes.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!