There is no way to optimize from the index. If you use group by and do not set the where condition, mysql has already read the entire table. And if there are millions of data, I personally do not recommend using sum directly to count the total number of each a in the table. The recommended optimization is this. 1. Establish scheduled tasks, temporary tables, and statistical tables 2. Read a certain amount of data regularly, record the statistical information of that data into the statistical table, and write the last id value of a certain amount of data as a record. Temporary tables. The id will be used as the condition when reading next time.
This segmented statistics can satisfy your two optimization conditions
There is no way to optimize from the index. If you use group by and do not set the where condition, mysql has already read the entire table. And if there are millions of data, I personally do not recommend using sum directly to count the total number of each a in the table. The recommended optimization is this.
1. Establish scheduled tasks, temporary tables, and statistical tables
2. Read a certain amount of data regularly, record the statistical information of that data into the statistical table, and write the last id value of a certain amount of data as a record. Temporary tables. The id will be used as the condition when reading next time.
This segmented statistics can satisfy your two optimization conditions
Let’s add the index to field A first
How to optimize GROUP BY in MySQL
Create a composite index (a, b), both SQL will perform index scan
In addition, statistical SQL must be done in a special report library, and timed and segmented statistics