如何在查询中有LIMIT时获得总结果数?

Sha*_*deh 6 mysql sql

我有这样的查询:

select * from table where id <= 10 limit 5;  // table has +10 rows
Run Code Online (Sandbox Code Playgroud)

上述查询^中的结果数为10行.现在我想知道,如何获得此查询中的总结果数:

select * from table where col = 'anything' limit 5;
Run Code Online (Sandbox Code Playgroud)

如何计算这个^ 中所有结果的数量(不管limit)

其实我想要这个号码:

select count(*) as total_number from table where col = 'anything'
Run Code Online (Sandbox Code Playgroud)

现在我想知道如何在没有其他查询的情况下获得总结果的数量.

pot*_*hin 10

添加一列,total例如:

select t.*
     , (select count(*) from tbl where col = t.col) as total
from tbl t
where t.col = 'anything'
limit 5
Run Code Online (Sandbox Code Playgroud)

@Tim Biegeleisen所述:limit关键字在其他所有内容之后应用,因此count(*)仍然会返回正确的答案.

  • 请注意,RDBMS表中的行表示无序集,因此没有ORDER BY的LIMIT是一个相当无意义的概念. (3认同)

Tha*_*kou 8

您需要查询中的SQL_CALC_FOUND_ROWS选项和FOUND_ROWS()函数来执行此操作:

DECLARE @rows int
SELECT SQL_CALC_FOUND_ROWS * from table where col = 'anything' limit 5;

SET @rows = FOUND_ROWS(); --for a later use
Run Code Online (Sandbox Code Playgroud)

  • 这是查找预限记录计数的正确方法. (2认同)
  • 作为*输出解决方案*,一切似乎都是正确的。但是为什么每一行都一次计数呢?我不相信。因此,这应该是正确的答案。 (2认同)