MySQL中LIMIT分页有什么优化方法

MySQL的分页语句没有Oralc或者SQL server那么方便

--语法:

SELECT * FROM table LIMIT [offset,] rows | rows OFFSET offset


--举例:

select * from table limit 5; --返回前5行

select * from table limit 0,5; --同上,返回前5行

select * from table limit 5,10; --返回6-15行

如何优化limit

当一个查询语句偏移量offset很大的时候,如select * from table limit 10000,10 , 最好不要直接使用limit,而是先获取到offset的id后,再直接使用limit size来获取数据。效果会好很多。

如:

select * From customers Where customer_id >=(
select customer_id From customers Order By customer_id limit 10000,1
) limit 10;


1、offset比较小的时候。 

 

      select * from yanxue8_visit limit 10,10 

      多次运行,时间保持在0.0004-0.0005之间http://www.zhutiai.com 

      Select * From yanxue8_visit Where vid >=( 

      Select vid From yanxue8_visit Order By vid limit 10,1 

      ) limit 10 

 

  多次运行,时间保持在0.0005-0.0006之间,主要是0.0006 

  结论:偏移offset较小的时候,直接使用limit较优。这个显然是子查询的原因。 

  2、offset大的时候。 

  

 

     select * from yanxue8_visit limit 10000,10 

      多次运行,时间保持在0.0187左右 

      Select * From yanxue8_visit Where vid >=( 

      Select vid From yanxue8_visit Order By vid limit 10000,1 

      ) limit 

 

10 

  多次运行,时间保持在0.0061左右,只有前者的1/3。可以预计offset越大,后者越优。 

  以后要注意改正自己的limit语句,优化一下Mysql了 


猜你喜欢

转载自blog.csdn.net/jiezking/article/details/80414012