Use LIMIT to paginate results in MySQL query(在 MySQL 查询中使用 LIMIT 对结果进行分页)
问题描述
我想一次获取一个页面"的结果;我希望页码是一个参数(在 JDBC 准备好的语句中).考虑以下代码片段
I want to fetch my results a 'page' at a time; I want the page number to be a parameter (in a JDBC prepared statement). Consider the following snippet
SELECT * FROM thread t ORDER BY t.id LIMIT ((? - 1) * 20), 20
理想情况下,这将导致第 1 页 LIMIT 0, 20
.
So ideally, this would result, for page 1, to LIMIT 0, 20
.
当我测试时
SELECT * FROM thread t ORDER BY t.id LIMIT ((1 - 1) * 20), 20
我被告知我有一个语法错误.不过,我不知道它可能是什么——这只是一些简单的数学运算.它告诉我的是
I am told I have a syntax error. I don't see what it could be, though - it's just some simple math. All it tells me is
ERROR 1064 (42000):您的 SQL 语法有错误;检查手册对应于您的 MySQL 服务器版本,以便在 '((1 -1) * 20),第 1 行 20'
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '((1 - 1) * 20), 20' at line 1
我的 LIMIT
子句有什么问题,我该如何解决?
What am I doing wrong with my LIMIT
clause, and how can I fix it?
推荐答案
MySQL 要求该 LIMIT 语法使用数字常量.
MySQL requires numeric constants for that LIMIT syntax.
来自 http://dev.mysql.com/doc/refman/5.7/en/select.html:
LIMIT 子句可用于限制 SELECT 语句返回的行数.LIMIT 接受一个或两个数字参数,它们都必须是非负整数常量,但以下情况除外:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions:
在准备好的语句中,可以使用 ?占位符.
Within prepared statements, LIMIT parameters can be specified using ? placeholder markers.
在存储的程序中,可以使用整数值的例程参数或局部变量指定 LIMIT 参数.
Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables.
在 Java 端计算常量.
Compute the constant on the Java side.
这篇关于在 MySQL 查询中使用 LIMIT 对结果进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 MySQL 查询中使用 LIMIT 对结果进行分页


- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01