简体   繁体   English

可以使用子查询在 MySql 查询中分配 LIMIT 值吗?

[英]Can use a subquery to assign LIMIT value in a MySql query?

I need extract de last rows of a table without no order.我需要在没有顺序的情况下提取表的最后一行。 I Try this but don't function:我试试这个,但不要 function:

SELECT * 
FROM contabilidad.emp001_series
LIMIT (SELECT COUNT(*)-10 AS TOTAL FROM contabilidad.emp001_series)

I need the result in natural order and can't use ORDER BY我需要自然顺序的结果,不能使用 ORDER BY

No. Subqueries are not allowed.不可以。不允许使用子查询。

Further, there is no such thing as "natural" order in a SQL table.此外,SQL 表中没有“自然”顺序。 SQL tables represent unordered sets. SQL 表表示无序集。

Your best bet is to do a reverse sort and start at the 11th row:最好的办法是进行反向排序并从第 11 行开始:

select s.*
from contabilidad.emp001_series s
order by id desc
limit 999999999 offset 10;

If you want an arbitrary set of ids, you could also use:如果你想要一组任意的 id,你也可以使用:

select s.*
from contabilidad.emp001_series s
where id < (select s2.id
            from contabilidad.emp001_series s2
            order by s2.id desc
            limit 1 offset 10
           );

Both of these assume you have a column of some sort that specifies the ordering.这两个都假设您有一个指定排序的某种列。

https://dev.mysql.com/doc/refman/8.0/en/select.html has detailed documentation about MySQL's SELECT statement including all its clauses. https://dev.mysql.com/doc/refman/8.0/en/select.html has detailed documentation about MySQL's SELECT statement including all its clauses.

It says:它说:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT 子句可用于限制 SELECT 语句返回的行数。 LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions: LIMIT 接受一个或两个数字 arguments,它们都必须是非负 integer 常量,但以下情况除外:

  • Within prepared statements, LIMIT parameters can be specified using?在准备好的语句中,可以使用?指定 LIMIT 参数? placeholder markers.占位符标记。

  • Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables.在存储的程序中,可以使用整数值的例程参数或局部变量来指定 LIMIT 参数。

Expressions, including subqueries, are not mentioned as legal argument in the LIMIT clause.表达式,包括子查询,在 LIMIT 子句中没有作为合法参数提及。

A simple solution would be to do your task in two queries: the first to get the COUNT() and then use that value as a constant value in the second query that includes the LIMIT.一个简单的解决方案是在两个查询中完成您的任务:第一个获取 COUNT(),然后在包含 LIMIT 的第二个查询中将该值用作常量值。

Not every task needs to be done in a single SQL statement.并非每项任务都需要在单个 SQL 语句中完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM