在 MySQL 的 LIMIT 子句中使用变量
我正在编写一个存储过程,其中有一个名为 my_size 的输入参数,它是一个 INTEGER。 我希望能够在 SELECT
语句的 LIMIT
子句中使用它。 显然这不受支持,有没有办法解决这个问题?
# I want something like:
SELECT * FROM some_table LIMIT my_size;
# Instead of hardcoding a permanent limit:
SELECT * FROM some_table LIMIT 100;
I am writing a stored procedure where I have an input parameter called my_size that is an INTEGER. I want to be able to use it in a LIMIT
clause in a SELECT
statement. Apparently this is not supported, is there a way to work around this?
# I want something like:
SELECT * FROM some_table LIMIT my_size;
# Instead of hardcoding a permanent limit:
SELECT * FROM some_table LIMIT 100;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
对于那些无法使用 MySQL 5.5.6+ 并且不想编写存储过程的人,还有另一种变体。 我们可以使用 ROWNUM 在子查询上添加 where 子句。
For those, who cannot use MySQL 5.5.6+ and don't want to write a stored procedure, there is another variant. We can add where clause on a subselect with ROWNUM.
存储过程
用法
在下面的示例中,它每次通过提供起始为 1 和 11 来检索 10 条记录。1 和 11 可能是作为 GET/POST 参数接收的页码分页。
STORED PROCEDURE
USAGE
In the following example it retrieves 10 records each time by providing start as 1 and 11. 1 and 11 could be your page number received as GET/POST parameter from pagination.
我知道这个答案来晚了,但请尝试 SQL_SELECT_LIMIT。
例子:
I know this answer has come late, but try SQL_SELECT_LIMIT.
Example:
搜索发现了这篇文章。 我已将相关文字粘贴在下面。
A search turned up this article. I've pasted the relevant text below.
MySQL 5.5.6 中已添加此功能。
检查此链接。
我已经升级到 MySQL 5.5,只是为了这个功能并且效果很好。
5.5 也有很多性能升级,我完全推荐它。
This feature has been added to MySQL 5.5.6.
Check this link out.
I've upgraded to MySQL 5.5 just for this feature and works great.
5.5 also has a lot of performance upgrades in place and I totally recommend it.
另一种方式,与“Pradeep Sanjaya”所写的相同,但使用 CONCAT:
Another way, the same as wrote "Pradeep Sanjaya", but using CONCAT:
从 MySQL 版本 5.5.6 开始,您可以使用变量/参数指定
LIMIT
和OFFSET
。有关参考,请参阅 5.5 手册,< a href="http://dev.mysql.com/doc/refman/5.6/en/select.html#idm140462371147952" rel="nofollow noreferrer">5.6 手册 和 @Quassnoi 的 答案
As of MySQL version 5.5.6, you can specify
LIMIT
andOFFSET
with variables / parameters.For reference, see the 5.5 Manual, the 5.6 Manual and @Quassnoi's answer
我在使用 MySql 5.0 时遇到了同样的问题,并在 @ENargit 的答案的帮助下编写了一个过程:
还包括通过记录总数查询获得的总行数。
I've faced the same problem using MySql 5.0 and wrote a procedure with the help of @ENargit's answer:
Also included the total rows obtained by the query with records_total.
您必须声明一个变量,然后设置它。 那么 LIMit 将会工作并将其放入 StoredProcedure 中,不确定它是否在正常查询中工作,
如下所示:
you must DECLARE a variable and after that set it. then the LIMIt will work and put it in a StoredProcedure not sure if it works in normal query
like this:
看来这里很多人都想用LIMIT作为参数而不用存储过程。
可以通过 PREPARE 和 EXECUTE 来完成,如下所示:
It seems that many people here want to use LIMIT as a parameter without stored procedures.
it can be done with PREPARE and EXECUTE like this: