Difference (1) and count (*) in the count of mysql

sql tuning, reduced mainly on account of: the number of physical reads and consistent gets.

count (1) and count (*) comparison:

If your data tables without primary keys, then count (1) than the count (*) fast
if there is a primary key, then the primary key (primary key) as a condition count also (*) faster than count
if your table has only one field, then that count (*) is the fastest of friends
compare count (*) count (1) both. Mainly to count (1) of the corresponding data fields.
If the count (1) is a poly index, id, it is certainly count (1) fast. But the difference is very small.
Because the count (*), automatically optimizes designated to that field. So no need to count (?), With the count (*), sql will help you complete optimization

Detailed count:

count(1)With count(主键)the same scan only the primary key.

count(*)Contact count(非主键):

  count (*) returns the total number of rows in the table include all existing row is null, but count (column names) returns the total number of rows in the table is removed except null (all columns will be included in the default values ).
  DISTINCT column name, the result would be the result of removing duplicate data is null and

count (primary key) is not necessarily faster than count (the rest of the index): 

Is the index structure of a B + tree, is stored in units of blocks. Assumed that the block size is 1K, the size of the primary key index 4B, there is a field size of the index A is 2B. 
Similarly a block 256 can be stored primary key index, but the index field 512 can store the A. 
2K is assumed that the total data item, means that the primary key index occupies eight blocks, while the field index A occupies blocks 4, with the primary key index needs to undergo multiple blocks when statistics, the number of multi-IO. A field efficiency slower than the index.

to sum up

 

1. If you really need to use in development count () polymerization, the priority count (*), because mysql database itself made a special optimized for the count (*).

Under primary key or primary key of the case, count (*) slightly faster than count (1) number. 
Count (1) than the count (*) fast without some of the primary key. 
If the table has only one field, count (*) is the fastest.
2. Use the count () function after polymerization, it is best not to tell where age = 1; these conditions will lead to taking the index, reduce the query efficiency. Unless the field has been established index. Use count () function after polymerization, if where condition, and the field where conditions are not indexed, the query will not take the index, a full table scan directly. 
3.count (field), the non-primary key field, is best not to use such an occurrence. Because it does not take the index.

Guess you like

Origin www.cnblogs.com/xiaozengzeng/p/12078845.html