Home Database Mysql Tutorial Mysql 分页语句Limit用法

Mysql 分页语句Limit用法

Jun 07, 2016 pm 03:34 PM
limit mysql Pagination usage statement

1、Mysql的limit用法 在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,这个时候怎么办呢?不用担心, mysql 已经为我们提供了这样一个功能。 Sql代码 SELECT * FROM table LIMIT[offset,] rows | rows OFFSEToffset LIMIT 子句可以被用于强

1、Mysql的limit用法

 

在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,这个时候怎么办呢?不用担心,mysql已经为我们提供了这样一个功能。

 

Sql代码  Mysql 分页语句Limit用法

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

 

LIMIT 子句可以被用于强制 SELECT 语句返回指定的记录数。LIMIT 接受一个或两个数字参数。参数必须是一个整数常量。如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1): 为了与 PostgreSQL 兼容,MySQL 也支持句法: LIMIT # OFFSET #。

 

Sql代码  Mysql 分页语句Limit用法

  1. mysql> SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15  
  2.   
  3. //为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:   
  4. mysql> SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.  
  5.   
  6. //如果只给定一个参数,它表示返回最大的记录行数目:   
  7. mysql> SELECT * FROM table LIMIT 5; //检索前 5 个记录行  
  8.   
  9. //换句话说,LIMIT n 等价于 LIMIT 0,n。  

 

    【引用,路人乙:Mysql中limit的用法详解】

 

2、Mysql的分页查询语句的性能分析

 

 

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

 

2.1最基本的分页方式:

 

Sql代码  Mysql 分页语句Limit用法

  1.    
  2. SELECT ... FROM ... WHERE ... ORDER BY ... LIMIT ...  
  

在中小数据量的情况下,这样的SQL足够用了,唯一需要注意的问题就是确保使用了索引:

举例来说,如果实际SQL类似下面语句,那么在category_id, id两列上建立复合索引比较好:

 

Sql代码  Mysql 分页语句Limit用法

  1. SELECT * FROM articles WHERE category_id = 123 ORDER BY id LIMIT 50, 10  
  

 

2.2子查询的分页方式:

 

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

Sql代码  Mysql 分页语句Limit用法

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

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

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

Sql代码  Mysql 分页语句Limit用法

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

 

2.3JOIN分页方式

 

Sql代码  Mysql 分页语句Limit用法

  1. SELECT * FROM `content` AS t1   
  2. JOIN (SELECT id FROM `content` ORDER BY id desc LIMIT ".($page-1)*$pagesize.", 1) AS t2   
  3. WHERE t1.id ORDER BY t1.id desc LIMIT $pagesize;   
  

    经过我的测试,join分页和子查询分页的效率基本在一个等级上,消耗的时间也基本一致。

explain SQL语句:

id select_type table type possible_keys key key_len ref rows Extra

1 PRIMARY system NULL NULL NULL NULL 1  

1 PRIMARY t1 range PRIMARY PRIMARY 4 NULL 6264 Using where

2 DERIVED content index NULL PRIMARY 4 NULL 27085 Using index

 

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

 

为什么会这样呢?因为子查询是在索引上完成的,而普通的查询时在数据文件上完成的,通常来说,索引文件要比数据文件小得多,所以操作起来也会更有效率。

 

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

【引用原文,energy1010的空间:MySql分页sql语句】

 

 

3、Oracle分页查询语句

Oralce数据库 

从数据库表中第M条记录开始检索N条记录 

Sql代码  Mysql 分页语句Limit用法

  1. SELECT * FROM (SELECT ROWNUM r,t1.* From 表名称 t1 where rownum 
  2.  where t2.r >= M   

  例如从表Sys_option(主键为sys_id)中从第10条记录开始检索20条记录,语句如下: 

Sql代码  Mysql 分页语句Limit用法

  1. SELECT * FROM (SELECT ROWNUM R,t1.* From Sys_option where rownum 
  2. Where t2.R >= 10   
  

3、MSSQLSERVER分页查询语句

 

SQL Server主要利用 SELECT TOP语句分页,具体方案,请参考

 

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

 

分页方案一:(利用Not In和SELECT TOP分页) 

语句形式: 

 

Sql代码  Mysql 分页语句Limit用法

  1. SELECT TOP 10 *   
  2. FROM TestTable   
  3. WHERE (ID NOT IN   
  4. (SELECT TOP 20 id   
  5. FROM TestTable   
  6. ORDER BY id))   
  7. ORDER BY ID   
   

Sql代码  Mysql 分页语句Limit用法

  1. SELECT TOP 页大小 *   
  2. FROM TestTable   
  3. WHERE (ID NOT IN   
  4. (SELECT TOP 页大小*页数 id   
  5. FROM 表   
  6. ORDER BY id))   
  7. ORDER BY ID   
  8. SELECT TOP 页大小 *   

Sql代码  Mysql 分页语句Limit用法

  1. FROM TestTable   
  2. WHERE (ID >   
  3. (SELECT MAX(id)   
  4. FROM (SELECT TOP 页大小*页数 id   
  5. FROM 表   
  6. ORDER BY id) AS T))   
  7. ORDER BY ID   
  

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

 

分页方案二:(利用ID大于多少和SELECT TOP分页) 

语句形式: 

Sql代码  Mysql 分页语句Limit用法

  1. SELECT TOP 10 *   
  2. FROM TestTable   
  3. WHERE (ID >   
  4. (SELECT MAX(id)   
  5. FROM (SELECT TOP 20 id   
  6. FROM TestTable   
  7. ORDER BY id) AS T))   
  8. ORDER BY ID   
  

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

分页方案三:(利用SQL的游标存储过程分页) 

 

Sql代码  Mysql 分页语句Limit用法

  1. create procedure XiaoZhengGe   
  2. @sqlstr nvarchar(4000), --查询字符串   
  3. @currentpage int--第N页   
  4. @pagesize int --每页行数   
  5. as   
  6. set nocount on   
  7. declare @P1 int--P1是游标的id   
  8. @rowcount int   
  9. exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output   
  10. select ceiling(1.0*@rowcount/@pagesize) as 总页数--,@rowcount as 总行数,@currentpage as 当前页   
  11. set @currentpage=(@currentpage-1)*@pagesize+1   
  12. exec sp_cursorfetch @P1,16,@currentpage,@pagesize   
  13. exec sp_cursorclose @P1   
  14. set nocount off   
  

其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。 

建议优化的时候,加上主键和索引,查询效率会提高。 

 

通过SQL 查询分析器,显示比较:我的结论是: 

分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句 

分页方案一:(利用Not In和SELECT TOP分页) 效率次之,需要拼接SQL语句 

分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用 

 

在实际情况中,要具体分析。 

 

【引用:在SQL Server中通过SQL语句实现分页查询 】

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

See all articles