mysql order by limit 使用注意事項


5.7以上重復數據問題

order by limit會出現數據重復問題

--查看mysql版本
select  version()
--創建表
create table student(
  id int(10) PRIMARY KEY auto_increment,
    name varchar(32),
    age int(3)
)
--插入數據
insert into student VALUEs(null,'小明',11);
insert into student VALUEs(null,'王小明',5);
insert into student VALUEs(null,'小二毛',11);
insert into student VALUEs(null,'王小三',4);
insert into student VALUEs(null,'毛小二',11);
insert into student VALUEs(null,'張小二',11);
--插入表
select * from student s
order by age desc
--分頁查詢
select * from(select * from student s
order by age desc LIMIT 0,1)tab
union all
select * from(select * from student s
order by age desc LIMIT 1,1)tab
union all
select * from(select * from student s
order by age desc LIMIT 2,1)tab
UNION ALL
select * from(select * from student s
order by age desc LIMIT 3,1)tab

我是5.6版本無法測試,5.7及其以上版本會出現 order by的列有相同的值時 同時未做索引時, mysql會隨機選取這些行 文檔地址:https://dev.mysql.com/doc/refman/5.7/en/limit-optimization.html

解決方式 可以增加一列含索引的排序字段

--分頁查詢
select * from(select * from student s
order by age desc,id asc LIMIT 0,1)tab
union all
select * from(select * from student s
order by age desc,id asc LIMIT 1,1)tab
union all
select * from(select * from student s
order by age desc,id asc LIMIT 2,1)tab
UNION ALL
select * from(select * from student s
order by age desc,id asc LIMIT 3,1)tab

limit深分頁查詢優化

select * from tab limit n,m     limit原理是先讀取前n條數據,讀取最后m條數據 所以n越大就越慢 性能也越差

注:以下測試數據有1100萬條

優化前

select * from `cpn_coupon_code`  c   limit 10000000,10

 

 

優化后

SELECT * FROM cpn_coupon_code  c
INNER JOIN (SELECT id FROM cpn_coupon_code e  LIMIT 10000000,10)tab on tab.id=c.id 

 

 與優化前版本是先查出數據id 然后根據id查數據

因為只查索引頁 索引 n,m     n就只會是索引 不會包含數據

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM