前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Mysql分页order by数据错乱重复

Mysql分页order by数据错乱重复

作者头像
traffic
发布2020-04-09 12:03:22
2.4K0
发布2020-04-09 12:03:22
举报
文章被收录于专栏:大龄码农大龄码农大龄码农

作久项目代码优化,公司用的是Mybatis,发现分页和排序时直接传递参数占位符用的都是 $,由于$有SQL注入风险,要改为#,但是封装page类又麻烦,所以直接使用了 pageHelper 插件了,方便快捷,但是测试时发现数据有问题:

//第二页
SELECT id, createtime, idnumber, mac FROM `tblmacwhitelist`  
ORDER BY idnumber DESC  
LIMIT    5 , 5;

//第三页
SELECT id, createtime, idnumber, mac FROM `tblmacwhitelist`  
ORDER BY idnumber DESC  
LIMIT    10 , 5

//第四页
SELECT id, createtime, idnumber, mac FROM `tblmacwhitelist`  
ORDER BY idnumber DESC  
LIMIT    15 , 5

分页数量正常,但这3条SQL的结果集是一样的,第二第三第四页的数据,一模一样,我一脸懵逼,后来查了mysql官方文档返现:

If multiple rows have identical values in the ORDER BY columns, the server is free to return those rows in any order, and may do so differently depending on the overall execution plan. In other words, the sort order of those rows is nondeterministic with respect to the nonordered columns. One factor that affects the execution plan is LIMIT, so an ORDER BY query with and without LIMIT may return rows in different orders.

大概意思是 :一旦 order by 的 colunm 有多个相同的值的话,结果集是非常不稳定

那怎么解决呢,其实很简单,就是order by 加上唯一不重复的列即可,即在后面加上一个唯一索引就可以了,

ORDER BY idnumber DESC , id DESC

//第二页
SELECT id, createtime, idnumber, mac FROM `tblmacwhitelist`  
ORDER BY idnumber DESC ,
id DESC
LIMIT    5 , 5;

//第三页
SELECT id, createtime, idnumber, mac FROM `tblmacwhitelist`  
ORDER BY idnumber DESC ,
id DESC
LIMIT    10 , 5

//第四页
SELECT id, createtime, idnumber, mac FROM `tblmacwhitelist`  
ORDER BY idnumber DESC  ,
id DESC
LIMIT    15 , 5

完美解决问题了。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档