从子查询结果获取限制值
我想在查询中使用 LIMIT 选项,但预期行数存储在另一个表中。这就是我所拥有的,但它不起作用:
select * from table1 limit (select limitvalue from table2 where id = 1)
当我只运行子查询时,结果是 6,正如预期的那样。
如果可能的话,我更喜欢使用WITH语句,但这也不起作用。 先感谢您!
I would like to use the LIMIT option in my query, but the number of expected rows is stored in another table. This is what I have, but it doesn't work:
select * from table1 limit (select limitvalue from table2 where id = 1)
When I only run the subquery, the result is 6, as expected.
I prefer working with a WITH statement if possible, but that didn't work eiter.
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用准备好的语句来获取来自其他表的查询限制,因为限制子句不允许非常量变量作为参数:
sql查询的来源来自另一篇文章
You could use a prepared statement to get the limit of queries from the other table because the limit clause does not allow non constant variables as parameter:
The source of the sql query from another post
您可以在 CTE 中使用 MariaDB 的
ROW_NUMBER
函数来计算要输出的行数,并将其与限制值
进行比较。例如:注意使用
LIMIT
而不使用ORDER BY
不能保证每次都能得到相同的结果。您应该在ROW_NUMBER
窗口函数的OVER
部分包含ORDER BY
子句。对于我的演示中的示例数据,您可以使用以下内容:dbfiddle 上的演示
You can make use of MariaDB's
ROW_NUMBER
function in a CTE to count the rows to be output, comparing that against thelimitvalue
. For example:Note Using
LIMIT
withoutORDER BY
is not guaranteed to give you the same results every time. You should include anORDER BY
clause in theOVER
part of theROW_NUMBER
window function. With the sample data in my demo, you might use something like:Demo on dbfiddle