Research on the usage and efficiency of count(*) and DISTINCT in Mysql

When dealing with a large amount of data database, I
suddenly found that mysql's different processing of count(*) will cause different results

For example, executing
SELECT count(*) FROM tablename
can return results very quickly even for tens of millions of data mysql,
while for
SELECT count(*) FROM tablename WHERE.....
mysql query time begins to climb

Carefully read the manual and found that when there is no WHERE statement to perform the count operation on the entire mysql table, the
MyISAM type table saves the total number of rows, and when a WHERE qualified statement is added, Mysql needs to retrieve the entire table
. get the value of count

I suddenly remembered that many new php programs I saw did not realize the processing of count very well.
By

the way, the DISTINCT keyword of mysql has many unexpected uses
. For
example, SELECT COUNT( DISTINCT id ) FROM tablename can be used to record records ;
it is to calculate the number of records with different ids in the talbebname table

2. When you need to return the specific values ​​of different id records, you can use
such as SELECT DISTINCT id FROM tablename;
return the specific values ​​of different ids in the talbebname table

3. In the above case 2, there will be ambiguity when it is necessary to return results with more than 2 columns in the mysql table,
such as SELECT DISTINCT id, type FROM tablename;
in fact, the returned result is that the id and type are different at the same time, that is, DISTINCT works at the same time The two fields must have the same id and tyoe to be excluded, which is not the same as the result we expected

4. At this time, you can consider using the group_concat function to exclude, but this mysql function is only supported above mysql4.1

5. In fact, there is another solution, which is to use
SELECT id, type, count(DISTINCT id) FROM tablename,
although such a return result has one more column of useless count data (maybe you need this useless data I said)
to return The result is that only all the results with different ids can be used complementary to the above 4 types, just to see what kind of data you need

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326843216&siteId=291194637