Mysql Index Tuning single table, two tables, three tables practice

 

Single table

New Table

CREATE TABLE IF NOT EXISTS article(
id INT(10) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
author_id INT(10) UNSIGNED NOT NULL,
category_id INT(10) UNSIGNED NOT NULL,
views INT(10) UNSIGNED NOT NULL,
comments INT(10) UNSIGNED NOT NULL,
title INT(10) UNSIGNED NOT NULL,
content TEXT NOT NULL
);

 

Insert data

INSERT INTO article(author_id,category_id,views,comments,title,content)VALUES
(1,1,1,1,'1','1'),
(2,2,2,2,'2','2'),
(1,1,3,3,'3','3');

 

Search For 

Query category_id case 1 is greater than 1 and comments, views the most article_id.

SELECT id,author_id FROM article WHERE category_id = 1 AND comments > 1 ORDER BY views DESC LIMIT 1;

  

Use EXPLAIN to view the execution plan

EXPLAIN SELECT id,author_id FROM article WHERE category_id = 1 AND comments > 1 ORDER BY views DESC LIMIT 1;

Conclusion: type is ALL, all queries appear as that worst-case scenario, Extra information Using filesort the worst of situations, need to be optimized.

 

Start optimizing

The first optimization
see the index:

show index from article;

At this point we optimized by indexing, but we do not know indexing to a column which is the most appropriate, it is necessary to try.

We first create a joint index, on three fields: category_id, comments, views.

Create and delete indexes:

create index ide_article_ccv on article(category_id,comments,views);
DROP INDEX ide_article_ccv ON article;

Conclusions:
of the type becomes the range, which can be tolerated, but the extra Using filesort still in use is unacceptable.
Why do we established index but to no avail?
This is in accordance with the principle BTree index
to sort category_id
If you encounter the same sort comments category_id then again, if you encounter the same comments reordering views,
when the comments field again field a joint in the middle position,
because comments> 1 condition a range of values (called range)
Mysql not use the index again later retrieval section views, i.e., the latter type of query field index is invalid range.

 

第二次优化:
create index ide_article_cv on article(category_id,views);

结论:type变成ref,Extra中的Using filesort也消失了,结果很理想。

 

 

保持更新中。。。

Guess you like

Origin www.cnblogs.com/-wenli/p/12182477.html