mysql中用limit 進行分頁有兩種方式
阿新 • • 發佈:2020-11-10
- 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程式碼
- mysql> SELECT * FROM table LIMIT 5,10; // 檢索記錄行 6-15
- //為了檢索從某一個偏移量到記錄集的結束所有的記錄行,可以指定第二個引數為 -1:
- mysql> SELECT * FROM table LIMIT 95,-1; // 檢索記錄行 96-last.
- //如果只給定一個引數,它表示返回最大的記錄行數目:
- 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(); } }