SELECT COUNT() vs mysql_num_rows();
我有一个大表 (60+) 数百万条记录.
I have a large table (60+) millions of records.
我正在使用 PHP 脚本来浏览此表.
I'm using PHP script to navigate through this table.
PHP 脚本(带分页)加载速度非常快,因为:
PHP script (with pagination) loads very fast because:
表引擎是 InnoDB 因此 SELECT COUNT()
很慢而且 mysql_num_rows()
不是一个选项,所以我保留总行数(我用来在一个单独的表中生成分页)(我在 DELETE
和 total_rows=total_rows-1
和 total_rows=total_rows1+1
和INSERT
).
The table engine is InnoDB thus SELECT COUNT()
is very slow and mysql_num_rows()
is not an option, so i keep the total row count (the number that i use to generate pagination) in a separate table (i update this record total_rows=total_rows-1
and total_rows=total_rows1+1
during DELETE
and INSERT
).
但问题是如何处理搜索结果的分页?
But the question is what to do with the pagination for search results?
现在我分两步做:
1.
$condition = " fname='rinchik' ";
$result = "SELECT * FROM my_large_table WHERE" . $condition;
这里我从数据库中获得了所有搜索结果.
Here i got all search results from DataBase.
2.现在我需要计算这些结果来创建分页.我正在这样做:
2. Now i need to count these results to create pagination. I'm doing this:
$condition; <- we already have this from the step 1
$result_count = "SELECT COUNT(id) FROM my_large_table WHERE" . $condition;
而且速度有点慢.
如果我这样做(只需一步)会更好吗?:
Would it be better if i will do it this way (with just one step)?:
$condition = " fname='rinchik' ";
$result = "SELECT * FROM my_large_table WHERE" . $condition;
$result_count = mysql_num_rows($result);
使用COUNT
,服务器内部会以不同的方式处理请求.
Use COUNT
, internally the server will process the request differently.
在执行COUNT
时,服务器只会分配内存来存储计数的结果.
When doing COUNT
, the server will only allocate memory to store the result of the count.
当使用mysql_num_rows
时,服务器将处理整个结果集,为所有这些结果分配内存,并将服务器置于获取模式,这涉及许多不同的细节,例如锁定.
When using mysql_num_rows
, the server will process the entire result set, allocate memory for all those results, and put the server in fetching mode, which involves a lot of different details, such as locking.
把它想象成以下伪场景:
Think of it like the following pseudo scenarios:
SELECT COUNT(*)
嘿鲍勃,教室里有多少人?
Hey Bob, how many people are in the class room?
mysql_num_rows
嘿鲍勃,把教室里的所有人都派给我,......我会自己数数来计算人数
Hey Bob, send all the people from the classroom over to me, ... I'll count them to get the number of people myself
总而言之,当使用 mysql_num_rows
时,您将所有记录传输到客户端,并且客户端必须自己计算计数.
In summary, when using mysql_num_rows
you are transferring all records to the client, and the client will have to calculate the count itself.