我可以在 LIMIT 偏移中使用 MySQL 函数吗

2022-01-15 00:00:00 limit offset mariadb mysql

我可以在 LIMIT 偏移中使用 MySQL 函数吗?喜欢:

Can I use MySQL functions in the LIMIT offset? Like:

SELECT * FROM sites WHERE ... LIMIT FLOOR(1 + RAND() * (SELECT COUNT(*) FROM sites)) , 1

推荐答案

不,你不能直接.LIMITOFFSET 值必须是常量.

No, you can't do that directly. LIMIT and OFFSET values must be constants.

来自MySQL 文档的引用:

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 (except when using prepared statements).

不过,您可以使用准备好的语句和变量:

You can use prepared statements and variables, though:

SELECT @offset:=FLOOR(1 + RAND() * COUNT(*)) FROM sites;
PREPARE STMT FROM 'SELECT * FROM sites WHERE ... LIMIT ?, 1';
EXECUTE STMT USING @offset; 

相关文章