Heim  >  Artikel  >  Backend-Entwicklung  >  php MySQL与分页效率_PHP教程

php MySQL与分页效率_PHP教程

WBOY
WBOYOriginal
2016-07-21 15:52:18756Durchsuche

 
最基本的分页方式:
SELECT ... FROM ... WHERE ... ORDER BY ... LIMIT ...
在中小数据量的情况下,这样的SQL足够用了,唯一需要注意的问题就是确保使用了索引:
举例来说,如果实际SQL类似下面语句,那么在category_id, id两列上建立复合索引比较好:
SELECT * FROM articles WHERE category_id = 123 ORDER BY id LIMIT 50, 10

子查询的分页方式:

随着数据量的增加,页数会越来越多,查看后几页的SQL就可能类似:

SELECT * FROM articles WHERE category_id = 123 ORDER BY id LIMIT 10000, 10

一言以蔽之,就是越往后分页,LIMIT语句的偏移量就会越大,速度也会明显变慢。

此时,我们可以通过子查询的方式来提高分页效率,大致如下:

SELECT * FROM articles WHERE category_id = 123 AND id >= (
    SELECT id FROM articles ORDER BY id LIMIT 10000, 1
) LIMIT 10

----------------------------------------

实际可以利用类似策略模式的方式去处理分页,比如判断如果是一百页以内,就使用最基本的分页方式,大于一百页,则使用子查询的分页方式。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/318979.htmlTechArticle最基本的分页方式: SELECT...FROM...WHERE...ORDERBY...LIMIT... 在中小数据量的情况下,这样的SQL足够用了,唯一需要注意的问题就是确保使用了索...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn