Data duplication problem during mysql order by limit paging

When we use mysql for data query, we often encounter the problem that the amount of data is too large and needs to be displayed by paging. At this time, we will use the limit keyword:

SELECT * FROM table LIMIT [param1,] param2;

The LIMIT clause can be used to force the SELECT statement to return the specified number of records. LIMIT accepts one or two numeric parameters. The parameter must be an integer constant. If two parameters are given, the first parameter specifies the offset of the first returned record line, and the second parameter specifies the maximum number of returned record lines. The offset of the initial record line is 0 (instead of 1).

Usually when using limit, order by will be used to sort the results, such as order by creation time desc.
However, it was found in the project that some problems will occur when the values ​​of the fields to be sorted are the same after order by.
Problem:
 Data paging needs to be reversed according to the create_time field of the data record creation time, that is, order by create_time desc is used, but we will find that the data obtained when the front-end requests is incorrect, and there is a certain amount of duplicate data in the paging.
First page of Insert picture description here
paging : Second page of paging:
Insert picture description here

Both pages of an order data tab appear.
Reason:
 If you specify an ORDER BY statement, SQL Server will sort the rows and return them in the requested order. However, if the order is not deterministic, that is, there may be repeated values, in each group with the same value, the order is "random" for the same reason as above.
Solution:
Ensure that the sorting field is unique or Add multiple sorting conditions
Insert picture description here
Summary: The
ORDER clause sorts the query results by one or more (up to 16) fields, which can be in ascending order (ASC) or descending order (DESC), and the default is ascending order. The ORDER clause is usually placed at the end of the SQL statement. When the conditions in the ORDER clause have repeated values, the data obtained is random. When multiple fields are defined in the ORDER clause, they are sorted in the order of the fields.

Guess you like

Origin blog.csdn.net/weixin_43828467/article/details/111193353