Research on the usage and efficiency of count (*) and DISTINCT in Mysql
The usage and efficiency of count (*) and DISTINCT in Mysql
When processing a large data database
Suddenly, it is found that different mysql processing of count (*) results in different results.
For example
SELECT count (*) FROM tablename
Even for mysql with tens of millions of data, results can be returned very quickly.
For
SELECT count (*) FROM tablename WHERE .....
Mysql Query time began to rise
Check the manual carefully and find that when there is no WHERE statement for the count operation on the entire mysql table
A MyISAM table stores the total number of rows. when a WHERE statement is added, Mysql needs to search the entire table.
To obtain the count value.
I suddenly remembered that many of the emerging php programs were not very aware of the count processing.
Record
By the way, mysql's DISTINCT keywords are of a lot of unexpected use.
1. it can be used when count does not repeat records
For example, select count (DISTINCT id) FROM tablename;
Calculate the number of records with different IDs in the talbebname table.
2. you can use
For example, select distinct id FROM tablename;
Returns the specific values of different IDs in the talbebname table.
3. in case 2 above, there will be ambiguity when you need to return results with more than two columns in the mysql table
For example, select distinct id, type FROM tablename;
In fact, the returned result is a result of different IDs and types, that is, DISTINCT serves two fields at the same time. it must be the same id and tyoe to be excluded. it is different from the expected result.
4. at this time, you can use the group_concat function for troubleshooting. However, this mysql function is supported only after mysql4.1.
5. Another solution is to use
SELECT id, type, count (DISTINCT id) FROM tablename
Although such a returned result contains a column of useless count data (you may need this useless data)
The returned result is that only the results with different IDs can be used in concert with the above four types. it depends on what data you need.
BitsCN.com