mysql中用limit 进行分页有两种方式

springboot分页插件的使用

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

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

Sql代码 复制代码 
  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 个记录行   
 
 
 

limit和offset用法

mysql里分页一般用limit来实现

1. select* from article LIMIT 1,3

2.select * from article LIMIT 3 OFFSET 1

上面两种写法都表示取2,3,4三条条数据

当limit后面跟两个参数的时候,第一个数表示要跳过的数量,后一位表示要取的数量,例如

select* from article LIMIT 1,3 就是跳过1条数据,从第2条数据开始取,取3条数据,也就是取2,3,4三条数据

当 limit后面跟一个参数的时候,该参数表示要取的数据的数量

例如 select* from article LIMIT 3  表示直接取前三条数据,类似sqlserver里的top语法。

当 limit和offset组合使用的时候,limit后面只能有一个参数,表示要取的的数量,offset表示要跳过的数量 。

例如select * from article LIMIT 3 OFFSET 1 表示跳过1条数据,从第2条数据开始取,取3条数据,也就是取2,3,4三条数据

 
 
 

在springboot工程下的pom.xml中添加依赖

复制代码
<!--分页 pagehelper -->
  <dependency>
       <groupId>com.github.pagehelper</groupId>
       <artifactId>pagehelper-spring-boot-starter</artifactId>
       <version>1.2.5</version>
   </dependency>
<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
</dependency>
复制代码

在工程的配置Application文件中添加如下代码

#pagehelper分页插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

对service层的更改

复制代码
@Service
public class UserService2 {
    @Autowired
    private UserDao userDao;
    public PageInfo<User> queryAll(Integer page, Integer pageSize ){
        PageHelper.startPage(page,pageSize);//分页起始码以及每页页数
        List<User> users=userDao.selectAll();
        PageInfo pageInfo=new PageInfo(users);
        return pageInfo;
    }
复制代码

对controller层的更改

复制代码
@Controller
public class UserController2 {
    @Autowired
    private UserService2 userService2;

    @RequestMapping("queryAll")
    @ResponseBody
    public List<User> query(@RequestParam(value="page",defaultValue="1")Integer page, @RequestParam(value="pageSize",defaultValue="2")Integer pageSize){
        PageInfo<User> pageInfo=userService2.queryAll(page,pageSize);
        return pageInfo.getList();
    }
}

原文地址:https://www.cnblogs.com/bruce1992/p/13949812.html