Home >Database >Mysql Tutorial >MySQL与分页_MySQL

MySQL与分页_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-01 14:00:58844browse

如果和MSSQL的TOP语法相比,那么MySQL的LIMIT语法要显得优雅了许多。使用它来分页是再自然不过的事情了。

  最基本的分页方式:

  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 aricles 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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn