在 MySQL 查询中使用 LIMIT 对结果进行分页 [英] Use LIMIT to paginate results in MySQL query

查看:55
本文介绍了在 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 对结果进行分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆