Detailed explanation of the problem of mixed use of limit and sum functions in MySQL

Detailed explanation of the problem of mixed use of limit and sum functions in MySQL

Preface

Today, after synchronizing the order data, a colleague chose to use the LIMIT and SUM() functions to calculate the total amount of the current page to compare the total amount of a specific order with the other party because there was a difference between the total order amount and the total amount of the data source. However, he found that the calculated amount was not the total amount of the paged orders, but the total amount of all orders.

The database version is MySQL 5.7. Below we will use an example to review the problem encountered.

Problem review

This review will use a very simple order table as an example.

Data preparation

The order table creation statement is as follows (I am lazy here and use the auto-increment ID. It is not recommended to use the auto-increment ID as the order ID in actual development)

CREATE TABLE `order` (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Order ID',
 `amount` decimal(10,2) NOT NULL COMMENT 'Order amount',
 PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

The SQL to insert an amount of 100 is as follows (execute 10 times)

INSERT INTO `order`(`amount`) VALUES (100);

So the total amount is 10*100=1000.

Problem SQL

Use limit to query the data in pages, and use the sum() function to calculate the total amount of the current page

SELECT 
  SUM(`amount`)
FROM
  `order`
ORDER BY `id`
LIMIT 5;

As mentioned above, the expected result is 5*100=500, but the actual result is 1000.00 (the decimal point is due to the data type).

Troubleshooting

In fact, if you have a certain understanding of the execution order of SELECT statements, you can quickly determine why the returned result is the total amount of all orders? Next, I will analyze the problem based on the execution sequence of the problematic SQL:

  1. FROM: The FROM clause is executed first, which determines that the query is the order table.
  2. SELECT: The SELECT clause is the second clause executed, and the SUM() function is also executed at this time.
  3. ORDER BY: The ORDER BY clause is the third clause executed, and it only has one result, which is the total amount of the order.
  4. LIMIT: The LIMIT clause is executed last, and at this time there is only one result in the result set (the total amount of the order)

Supplementary content

Here is the execution order of SELECT statement

  1. FROM <left_table>
  2. ON <join_condition>
  3. <join_type> JOIN <right_table>
  4. WHERE <where_condition>
  5. GROUP BY <group_by_list>
  6. HAVING <having_condition>
  7. SELECT
  8. DISTINCT <select_list>
  9. ORDER BY <order_by_condition>
  10. LIMIT <limit_number>

Solution

When you need to count paging data (in addition to the SUM() function, the common COUNT(), AVG(), MAX(), and MIN() functions also have this problem), you can choose to use a subquery to handle it (PS: memory calculation is not considered here, and the purpose is to use the database to solve this problem). The solution to the above problem is as follows:

SELECT 
  SUM(o.amount)
FROM
  (SELECT 
    `amount`
  FROM
    `order`
  ORDER BY `id`
  LIMIT 5) AS o;

The return value of the operation is 500.00.

Summarize

The above is the full content of this article. I hope that the content of this article will have certain reference learning value for your study or work. Thank you for your support of 123WORDPRESS.COM.

You may also be interested in:
  • MySQL query optimization: LIMIT 1 avoids full table scan and improves query efficiency
  • Why does MySQL paging become slower and slower when using limit?
  • MySQL optimization query_cache_limit parameter description
  • Detailed explanation of the pitfalls of mixing MySQL order by and limit
  • Simple example of limit parameter of mysql paging
  • Reasons and optimization solutions for slow MySQL limit paging with large offsets
  • Mysql sorting and paging (order by & limit) and existing pitfalls
  • How to use MySQL limit and solve the problem of large paging
  • How to improve MySQL Limit query performance
  • Detailed explanation of MySQL Limit performance optimization and paging data performance optimization
  • A brief discussion on the implementation of MySQL's limit paging optimization solution
  • The impact of limit on query performance in MySQL

<<:  How to use Linux to calculate the disk space occupied by timed files

>>:  A simple way to implement Vue's drag screenshot function

Recommend

Solve the problem of yum installation error Protected multilib versions

Today, when installing nginx on the cloud server,...

javascript implements web version of pinball game

The web pinball game implemented using javeScript...

vue-table implements adding and deleting

This article example shares the specific code for...

Detailed explanation of MySQL database index

Table of contents 1. Introduction to MySQL Index ...

JS+CSS to realize dynamic clock

This article example shares the specific code of ...

Practice of multi-layer nested display of element table

There is a requirement for a list containing mult...

Detailed explanation of MySql slow query analysis and opening slow query log

I have also been researching MySQL performance op...

jQuery implements accordion small case

This article shares the specific code of jQuery t...

vue-amap installation and usage steps

I have previously shared the usage of asynchronou...

Source code reveals why Vue2 this can directly obtain data and methods

Table of contents 1. Example: this can directly g...

Tutorial on installing php5, uninstalling php, and installing php7 on centos

First, install PHP5 very simple yum install php T...

Use the sed command to modify the kv configuration file in Linux

sed is a character stream editor under Unix, that...

Detailed explanation of three solutions to the website footer sinking effect

Background Many website designs generally consist...