Count optimization of MySQL optimization

Optimize the count query

select count(*) from employees where id > 40000;

optimize it to the following statement

select (select count(*) from employees) - count(*) from employees where id <= 40000;

carry out testing

insert image description here
Since there are 90551 pieces of data with id>40000 and 20557 pieces of data with id<40000, can it be optimized if a subtraction operation is performed?

InnoDB engine

Design the employees table as an InnoDB engine and check its execution time.
The above two statements (15, 16) are the execution of the InnoDB engine.
insert image description here
It can be found that after the original statement is modified, the execution time is changed from 0.038s to 0.050s, which is slower. This is not optimized to ah?
Use the explain statement to view the execution plan, and find that the original statement scanned 55493 rows of data, and the type type is range, and the id_index index is used. The rows of the modified statement SUBQUERY show that 110,986 rows of data have been scanned in the entire table, and the rows of PRIMARY have scanned 19,623 rows of data, which means that the count(*) on the left side of the minus sign also scans the entire table, which is impossible at all. optimization.

Original sentence:

insert image description here

Modified statement:

insert image description here

MyISAM engine

After modifying the employees table to the MyISAM engine, check the execution time. The
above two statements (17, 18) are the execution of the MyISAM engine.
insert image description here
It can be found that after modifying the original statement, the execution time is changed from 0.034s to 0.004s, which is much faster.
to view the execution plan

Original sentence:

By default, the MyISAM engine saves a count(*) result, but if there is a where condition, MyISAM's operation on it is a full table scan.
insert image description here

Modified statement:

insert image description here
It can be found that the scanned rows are actually 1. This is because MyISAM stores a copy of count(*) by default. Therefore, if count() is optimized in this way under the MyISAM engine, the query speed can be greatly improved.

Guess you like

Origin blog.csdn.net/weixin_45930241/article/details/125269733