简体   繁体   中英

How to optimize mysql query with COUNT(*) and GROUP BY

I have the original table of 4 columns, described as follows:

+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| FieldID  | varchar(10) | NO   | MUL | NULL    |       |
| PaperID  | varchar(10) | NO   |     | NULL    |       |
| RefID    | varchar(10) | NO   |     | NULL    |       |
| FieldID2 | varchar(10) | NO   | MUL | NULL    |       |
+----------+-------------+------+-----+---------+-------+

I want to run a query with COUNT(*) and GROUP BY :

select FieldID, FieldID2, count(*) from nFPRF75_1 GROUP BY FieldID, FieldID2

I've created indexes on both column FieldID and column FieldID2, however, they seem to be ineffective. I have also tried OPTIMIZE table_name and created redundant indexes on these two columns (as is indicated by other optimization questions), unfortunately it didn't work out either.

Here is what I get from EXPLAIN :

 | id | select_type | table     | type | possible_keys | key  | key_len | ref  | rows     | Extra                           |
 +----+-------------+-----------+------+---------------+------+---------+------+----------+---------------------------------+
 |  1 | SIMPLE      | nFPRF75_1 | ALL  | NULL          | NULL | NULL    | NULL | 90412507 | Using temporary; Using filesort |

I wonder if there's anyway that I can use indexes in this query, or any other way to optimize it. Now it's of very low efficiency since there's lots of lines.

Thanks a lot for the help!

您应该创建(FieldID,FieldID2)的多列索引。

Create an index of FieldID, FieldID2 if you are grouping by them. That must improve the speed.

Also, I recommend you change count(*) to count('myIntColumn') which improve the speed too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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