mysql order by limit Precautions

5.7 or more duplicate data problem

order by limit data duplication problems occur

- Check mysql version of 
the SELECT   Version ()
 - Create a table 
the Create  the Table Student (
  id int(10) PRIMARY KEY auto_increment,
    name varchar(32),
    age int(3)
)
- inserting data 
INSERT  INTO Student VALUES ( null , ' Bob ' , . 11 );
 INSERT  INTO Student VALUES ( null , ' John Smith ' , . 5 );
 INSERT  INTO Student VALUES ( null , ' small wool ' , . 11 );
 INSERT  INTO Student VALUES ( null , ' Wang three ' , 4);
 INSERT  INTO Student VALUES ( null , ' wool two small ' , 11 );
 INSERT  INTO Student VALUES ( null , ' Zhang two ' , 11 );
 - inserting table 
SELECT  *  from Student S
 Order  by Age desc 
- tab Discover 
the SELECT  *  from ( the SELECT  *  from Student S
 the 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

I was unable to test the version 5.6, version 5.7 and above will also not done when the index, mysql will randomly select rows documents address when order by columns have the same value: https://dev.mysql.com/doc/ refman / 5.7 / en / limit- optimization.html

Solution can increase a sort field with index

--分页查询
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 deep paging query optimization

select * from tab limit n, m limit principle is to read the first n data, it reads the last n m data can be greater the more chronic worse

Optimization ago

select * from `cpn_coupon_code`  c   limit 10000000,10

 

 

Optimized

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就只会是索引 不会包含数据

 

Guess you like

Origin www.cnblogs.com/LQBlog/p/12208536.html