MySql 5.7 同時使用order by和limit時結(jié)果集不正確的問題
工作中寫的一句sql根據(jù)日期排序后進行分頁,結(jié)果缺失了一些數(shù)據(jù),且出現(xiàn)了重復(fù)的數(shù)據(jù)。
在sql不斷的調(diào)整嘗試后發(fā)現(xiàn),在同時使用order by和limit后的結(jié)果集和使用order by之后的結(jié)果集不一致。
原文如下:
If you combine LIMIT row_count with ORDER BY, MySQL stops sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast. If a filesort must be done, all rows that match the query without the LIMIT clause are selected, and most or all of them are sorted, before the first row_count are found. After the initial rows have been found, MySQL does not sort any remainder of the result set.
One manifestation of this behavior is that an ORDER BY query with and without LIMIT may return rows in different order, as described later in this section.
大概意思:
如果你把order BY 和 limit N 混合使用,mysql會在找排序結(jié)果中的第一個 “第N條記錄” 時就停止,而不會排序整個結(jié)果集。如果排序是通過索引完成的,那么這個操作就會非???。如果必須要通過數(shù)據(jù)文件排序,所有符合查詢條件的記錄都將被選中,并且所有的數(shù)據(jù)都將被排序,直到第一個 “第N條記錄” 被找到。在第一條的數(shù)據(jù)都被找到之后,mysql不會繼續(xù)把結(jié)果中剩余的數(shù)據(jù)進行排序。
這種實現(xiàn)行為的表現(xiàn)之一就是order by查詢 在配合 limit 使用和不配合limit使用的情況下的返回值,排序情況是不同的
解決方案是在order by后面再加上一個字段id asc作為排序條件。