简体   繁体   English

使用count(*)vs num_rows

[英]Using count(*) vs num_rows

To get number of rows in result set there are two ways: 要获得结果集中的行数,有两种方法:

  1. Is to use query to get count 是使用查询来获取计数

    $query="Select count(*) as count from some_table where type='t1'";

    and then retrieving the value of count. 然后检索count的值。

  2. Is getting count via num_rows(), in php. 在php中通过num_rows()获取计数。

so which one is better performance wise? 那么哪一个更好的表现呢?

If your goal is to actually count the rows, use COUNT(*) . 如果您的目标是实际计算行数,请使用COUNT(*) num_rows is ordinarily (in my experience) only used to confirm that more than zero rows were returned and continue on in that case. num_rows通常(根据我的经验)仅用于确认返回的行数超过零并且在这种情况下继续。 It will probably take MySQL longer to read out many selected rows compared to the aggregation on COUNT too even if the query itself takes the same amount of time. 即使查询本身花费相同的时间,与COUNT上的聚合相比,读取许多选定的行也可能需要更长的时间。

count is much more efficient both performance wise and memory wise as you're not having to retrieve so much data from the database server. 由于您不必从数据库服务器检索如此多的数据,因此计数在性能和内存方面都要高效得多。 If you count by a single column such as a unique id then you can get it a little more efficient 如果您按单个列(例如唯一ID)进行计数,那么您可以更高效地获得它

There are a few differences between the two: 两者之间存在一些差异:

  1. num_rows is the number of result rows (records) received. num_rows是收到的结果行(记录)的数量。
  2. count(*) is the number of records in the database matching the query. count(*)是与查询匹配的数据库中的记录数。

The database may be configured to limit the number of returned results (MySQL allows this for instance), in which case the two may differ in value if the limit is lower than the number of matching records. 数据库可以配置为限制返回结果的数量(例如MySQL允许这样做),在这种情况下,如果限制低于匹配记录的数量,则两者的值可能不同。 Note that limits may be configured by the DBA, so it may not be obvious from the SQL query code itself what limits apply. 请注意,限制可能由DBA配置,因此从SQL查询代码本身可能不明显适用的限制。

Using num_rows to count records implies "transmitting" each record, so if you only want a total number (which would be a single record/row) you are far better off getting the count instead. 使用num_rows来计算记录意味着“传输”每条记录,因此如果您只想要一个总数(这将是一个记录/行),那么您最好不要获得count

Additionally count can be used in more complex query scenario's to do things like sub-totals, which is not easily done with num_rows . 此外, count可用于更复杂的查询场景,以执行子总计等操作,而这不是使用num_rows轻松完成的。

It depends on your implementation. 这取决于您的实施。 If you're dealing with a lot of rows, count(*) is better because it doesn't have to pass all of those rows to PHP. 如果你正在处理很多行,count(*)会更好,因为它不必将所有这些行传递给PHP。 If, on the other hand, you're dealing with a small amount of rows, the difference is negligible. 另一方面,如果您处理少量行,则差异可以忽略不计。

如果你有少量的行, num_rows()会更好,如果有大量的行, count(*)会给你性能,你必须选择一个并发送给php。

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

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