简体   繁体   English

MySQL计算总行数

[英]MySQL count total number of rows

I have a complicated MySQL query which takes a lot of time, selecting from a table with more than 150k rows and several JOINS and subqueries. 我有一个复杂的MySQL查询,需要花费很多时间,从一个行超过150k的表和几个JOINS和子查询中进行选择。 I am limiting the amount of results, but I need to know the total amount of rows. 我限制了结果的数量,但我需要知道总行数。

Is there a way not to repeat the query with COUNT(*) as the field to get them? 有没有办法不用COUNT(*)重复查询作为获取它们的字段? (repeating the query almost doubles the amount of time the script takes to complete) (重复查询几乎使脚本完成所需的时间翻倍)

MySQL has a clause called SQL_CALC_FOUND_ROWS which you put after SELECT and before any field names. MySQL有一个名为SQL_CALC_FOUND_ROWS的子句,它放在SELECT之后和任何字段名之前。 Then you call a second query which is just SELECT FOUND_ROWS() AS rows and it gives you how many rows the previous query found. 然后调用第二个查询,它只是SELECT FOUND_ROWS() AS rows ,它给出了上一个查询找到的行数。

It may actually be faster to make the two queries (so you may just want to do some quick testing): 实际上两个查询可能会更快(所以你可能只想做一些快速测试):

In any case, try to make sure that the COUNT(*) can use the index (it will say "using index" in the Extra column if you use EXPLAIN query) 在任何情况下,尝试确保COUNT(*)可以使用索引(如果使用EXPLAIN查询,它将在Extra列中说“using index”)

You could also consider caching the COUNT(*) result if it doesn't have to be exact (as you're limiting your result). 您也可以考虑缓存COUNT(*)结果,如果它不必是精确的(因为您限制了结果)。

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

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