1. Test Environment
OS: Linux
DB: mysql-5.5.18
Table: innodb Storage Engine
The table is defined as follows:
2. test scenario and analysis [number of group_message records in the statistical table]
(1) select count (*) Method
(2) select count (1) Method
(3) select count (col_name) Method
Use
Select count (group_id)
Select count (user_id)
Select count (col_null)
The test results show that both select count (*) and select count (1) use the minimum secondary index group_id. Some may ask why we don't need a shorter primary key index [int type]. This is mainly because, in the innodb Storage engine, the primary key index actually contains indexes and data, scanning primary key indexes is actually scanning physical records at the largest cost. Let's take a look at several select count (col_name), count (group_id) uses the shortest secondary index, because this column is the index column, and count (user_id) uses the composite index, because user_id cannot actually use this index, but the number of records can also be obtained by scanning the index, which is less costly than scanning physical records, this should be an optimization of mysql; count (col_null) you cannot use indexes because the column contains null values, which is the lowest efficiency. In addition, for rows with null values, count (col_null) does not actually count, which is inconsistent with the original intention of counting the number of records in the table. For example, the test table has 852226 records, however, if the col_null column has only one non-empty row, the statistical result is as follows:
3. test conclusion
In mysql, when you need to count the number of records in the selct count table, use count (*) or count (1.