MySQL uses the sum index to Increase the efficiency by at least 100%.

Source: Internet
Author: User

There are two tables, Table

 CREATE TABLE `a` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`fid` smallint(6) unsigned NOT NULL DEFAULT '0',
`cnt` smallint(6) unsigned NOT NULL DEFAULT '0',
...
...
...
PRIMARY KEY (`id`),
KEY `idx_fid` (`fid`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8

Table B

 CREATE TABLE `b` 
(`fid` smallint(6) unsigned NOT NULL AUTO_INCREMENT,
`name` char(50) NOT NULL DEFAULT '',
...
...
...
PRIMARY KEY (`fid`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8

The SQL statement is as follows:

 SELECT COUNT(*) AS num1, SUM(a.cnt)+COUNT(*) AS num2
FROM a, b
WHERE b.fid='10913' AND a.fid=b.fid

Let's take a look at the execution plan:

We can see that the number of scanned rows is 229049, And the execution time is:

Terrible. Run set profiling = 1. Let's see where the time is consumed?

It takes a long time to sending data. What does sending data do during this time? Let's take a look at this: http://renxijun.blog.sohu.com/82906360.html

It is preparing data for the SELECT statement. solution:

Index creation:

 create index idx_fid_cnt on a (fid,cnt);

 

Let's look at the execution plan and time:

Conclusion: Using an appropriate index is a doubling of SQL efficiency. functions like sum include min () and max (), which all need to be indexed on fields.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.