MySQL - 07 explain usage

MySQL explain usage

A, explain the application command

The way to query data

1. Full table scan

1) In the statement explain the result type is ALL

2) When does a full table scan?

  • 2.1 Business really want to get all the data
  • 2.2 does not take the index due to a full table scan
    • 2.2.1 No Index
    • 2.2.2 Creating an index in question
    • 2.2.3 The statement in question

Production, performance mysql when using the full table scan is extremely poor, so MySQL try to avoid full table scan

2. index scan

2.1 Common Index Scan type:
. 1) full-index scan index
2) reaches the level range when the range query range
3) ref prefix unique non-unique index scans or scan index
. 4) eq_ref
. 5) const
. 6) System
. 7) null

From top to bottom, from worst to best performance, we believe that to reach at least the level range

Generally, we say, as long as a SQL statement, to range level, we think that efficiency index is OK

Full table scan:

mysql> explain select * from student2;

index : full index scan, index and index types to distinguish ALL traversing the index tree only.

mysql> explain select cno from course;
+----+-------------+--------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table  | type  | possible_keys | key     | key_len | ref  | rows | Extra       |
+----+-------------+--------+-------+---------------+---------+---------+------+------+-------------+
|  1 | SIMPLE      | course | index | NULL          | PRIMARY | 8       | NULL |    2 | Using index |
+----+-------------+--------+-------+---------------+---------+---------+------+------+-------------+
1 row in set (0.00 sec)

range : when the scope of the query will reach the level range

mysql> explain select * from city where population>30000000;
+----+-------------+-------+-------+---------------+----------+---------+------+------+-----------------------+
| id | select_type | table | type  | possible_keys | key      | key_len | ref  | rows | Extra                 |
+----+-------------+-------+-------+---------------+----------+---------+------+------+-----------------------+
|  1 | SIMPLE      | city  | range | idx_city      | idx_city | 4       | NULL |    1 | Using index condition |
+----+-------------+-------+-------+---------------+----------+---------+------+------+-----------------------+

REF : using a non-unique index scans or scan a prefix unique index matching rows returns a separate value.

mysql> explain select * from city where countrycode='chn';
+----+-------------+-------+------+---------------+-------------+---------+-------+------+-----------
| id | select_type | table | type | possible_keys | key         | key_len | ref   | rows | Extra   | 
+----+-------------+-------+------+---------------+-------------+---------+-------+------+-----------
|  1 | SIMPLE      | city  | ref  | CountryCode   | CountryCode | 3       | const |  363 | Using index condition |
+----+-------------+-------+------+---------------+-------------+---------+-------+------+-----------
1 row in set (0.00 sec)

#union all 比in 的速度快很多
mysql> explain select * from city where countrycode='CHN' union all select * from city where countrycode='USA';
+----+--------------+------------+------+---------------+-------------+---------+-------+------+-----------------------+
| id | select_type  | table      | type | possible_keys | key         | key_len | ref   | rows | Extra                 |
+----+--------------+------------+------+---------------+-------------+---------+-------+------+-----------------------+
|  1 | PRIMARY      | city       | ref  | CountryCode   | CountryCode | 3       | const |  363 | Using index condition |
|  2 | UNION        | city       | ref  | CountryCode   | CountryCode | 3       | const |  274 | Using index condition |
| NULL | UNION RESULT | <union1,2> | ALL  | NULL          | NULL        | NULL    | NULL  | NULL | Using temporary       |
+----+--------------+------------+------+---------------+-------------+---------+-------+------+-----------------------+
3 rows in set (0.00 sec)

eq_ref : REF Similarly, the difference in the index using a unique index for each index key, only one record in the table match, simply put, is to use a multi-table join as a primary key or a unique key associated condition A

join B 
on A.sid=B.sid
mysql> explain select score.mark,student.sname from score join student on score.sno=student.sno;

const, System : when a part of MySQL query optimization, and converted to a constant, using these types of access.

As will be placed where the primary key list, MySQL the query can be converted to a constant

mysql> explain select * from course where cno=1;

NULL : MySQL decomposition statement in the optimization process, even without access to a table or index when performing, for example, selected from an indexed column in the minimum can be done through a separate index lookup.

#查询超出范围
mysql> explain select * from course where cno>66666666666666666666666; 
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra                                               |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
|  1 | SIMPLE      | NULL  | NULL | NULL          | NULL | NULL    | NULL | NULL | Impossible WHERE noticed after reading const tables |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
1 row in set (0.00 sec)

Two, Extra (extended)

Using temporary Using filesort use the default file ordering (if you use the index, will avoid such sort)
the Using the Join Buffer

If there is no index on Using filesort check the order by, group by, distinct, join conditions are

mysql> explain select * from city where countrycode='CHN' order by population;

When the order by statement appears Using filesort, then try to make the value of the sort found in conditions where

mysql> explain select * from city where population>30000000 order by population;
mysql> select * from city where population=2870300 order by population;
+------+-------------------+-------------+----------+------------+
| ID   | Name              | CountryCode | District | Population |
+------+-------------------+-------------+----------+------------+
| 1899 | Nanking [Nanjing] | CHN         | Jiangsu  |    2870300 |
+------+-------------------+-------------+----------+------------+
1 row in set (0.00 sec)

key_len : the smaller the better

  • Prefix index to control

rows : the smaller the better


III. Indexing principles (norms)

In order to make more efficient use of the index, when creating the index, you must consider creating an index and what type of indexes created on which fields.

Then the index design principle is what?

  • 1, try to use a unique index

Unique index value is unique and can be more quickly determined by the particular record index.

For example:
students school table number is unique in the field. A student of information can quickly determine the field for the establishment of a unique index.
If you use a name, then there may be a phenomenon of the same name, in order to reduce the query speed.
Primary key index and a unique key index, used in the query is the most efficient.

#查看行数
mysql> select count(*) from world.city;
+----------+
| count(*) |
+----------+
|     4079 |
+----------+
1 row in set (0.01 sec)
#去重后的行数
mysql> select count(distinct countrycode) from world.city;
+-----------------------------+
| count(distinct countrycode) |
+-----------------------------+
|                         232 |
+-----------------------------+
1 row in set (0.00 sec)


mysql> select count(distinct countrycode,population ) from world.city;
+-----------------------------------------+
| count(distinct countrycode,population ) |
+-----------------------------------------+
|                                    4052 |
+-----------------------------------------+
1 row in set (0.01 sec)

Note: If the repeat value more, we can consider joint index

  • 2. It is often necessary to sort, group and joint field operations indexing

For example:
often need ORDER BY, field GROUP BY, DISTINCT and UNION operations such as sorting operation will waste a lot of time.
If indexing it, can effectively avoid the sort operations

  • 3. Indexed field often as the query conditions

    If a field is often used to make the query, the query speed of the field will affect the entire table query speed.

    Therefore, indexing this field, it can speed up the search the entire table.

    • 3.1 regular query
    • Duplicate values ​​less value 3.2

Note: If you often as a condition of the column, particularly duplicate values, you can create a joint index

  • 4. Try to use the prefix to index

If the value of the index field is very long, a prefix is preferably used to index values. For example, TEXT, and BLOG type of field, full-text search
would be a waste of time. If the foregoing fields retrieve only several characters, this can increase retrieval speed.


  • 5. Limit the number of index
    number of indexes is not better. Each index uses disk space, the more the index, the greater the required disk space.
    When you modify the table, the index of remodeling and updating a lot of trouble. The more the index, will update the table becomes a waste of time.
  • 6. Delete the index is no longer used or rarely used
    data in the table is a large number of updates, or use the data is changed after some of the original index may no longer be needed. Database management
    officer shall regularly find these indexes, delete them, thus reducing the impact on the index update operation.

-----------------------------------------------------------------------------------------------------------------------------------------------------

Focus:

  • 1. There is no query, or query is not indexed, do not take the index
#全表扫描
select * from table;
select  * from tab where 1=1;

In the service database, in particular the large amount of data tables, there is no such demand full table scan.
1) users for viewing is very painful.
2) to the server in terms of devastating.
3) SQL rewrite the following statement:

#情况1
#全表扫描
select * from table;
#需要在price列上建立索引
selec  * from tab  order by  price  limit 10;
#情况2
#name列没有索引
select * from table where name='zhangsan'; 
1、换成有索引的列作为查询条件
2、将name列建立索引
  • 2. The query result set is the most original data in the table, it should be more than 25%
mysql> explain select * from city where population>3000 order by population; 
mysql> explain select * from city where population>3000 limit 10;

1) If the service allowed, the control limit can be used.
2) combination of business judgment, there is no better way. If not better rewrite the program as much as possible not to store this data in a mysql, redis put inside.

  • 3. The index itself fails, the statistics untrue

    Index has the ability to self-maintenance.
    For the next table content changes frequently cases, there may be a failure of the index.
    Rebuild the index can be resolved

  • 4. The query function or use of the index columns in the index column operation, including operation (+, -, *, etc.)

mysql> explain select * from student2 where sid-1=8;
#例子
错误的例子:select * from test where id-1=9; 
正确的例子:select * from test where id=10;
  • The implicit conversion lead to failure of the index. This should pay attention to. Also in development often mistake
mysql> create table test (id int ,name varchar(20),telnum varchar(10));
mysql> insert into test values(1,'zs','110'),(2,'l4',120),(3,'w5',119),(4,'z4',112);
mysql> explain select * from test where telnum=120;
mysql> alter table test add index idx_tel(telnum);
mysql> explain select * from test where telnum='120';
  • 6. <>, Not in the index do not go
mysql> select * from tab where telnum <> '1555555';
mysql> explain select * from tab where telnum <> '1555555';

Single>, <, in likely to go, it may not go, and the result set about, try to combine business Add limit
or try to change or in union. Recommended use union all union queries.

 explain select * FROM teltab WHERE telnum IN ('110','119');
#改写成
explain select * FROM teltab WHERE telnum='110'
union all
select * FROM teltab WHERE telnum='119'
  • 7. like "% _" percent sign on top do not go
#走range索引扫描
explain select * from teltab WHERE telnum like '31%';
#不走索引
explain select * from teltab WHERE telnum like '%110';

% linux% Class search needs, you can use ------- elasticsearch> ELK (this is the underlying search engine, Baidu, Google is used)

  • 8. Joint reference index column other than the first position index in a separate
CREATE TABLE t1 (id INT,NAME VARCHAR(20),age INT ,sex ENUM('m','f'),money INT);
ALTER TABLE t1 ADD INDEX t1_idx(money,age,sex);
DESC t1
SHOW INDEX FROM t1
#走索引的情况测试
explain select name,age,sex,money from t1 where money=30 and age=30  and sex='m';
#部分走索引
explain select name,age,sex,money from t1 where money=30 and age=30;
explain select name,age,sex,money from t1 where money=30  and sex='m'; 
#不走索引
explain select name,age,sex,money from t1 where age=20
explain select name,age,sex,money from t1 where age=30 and sex='m';
explain select name,age,sex,money from t1 where sex='m';

to sum up:

If a SQL statement, a query is slow, check order:

1. Is there an index is created

2. View data types, and query whether the same

3. Query statement, whether to use the field to do arithmetic

4. check out the result set is large, limit

5. Query whether to use <statement> or not in

6. Does the query use fuzzy queries, and in front of the%

7. If a joint index, query in order to create an index

8. index corruption

Guess you like

Origin www.cnblogs.com/gongjingyun123--/p/11832402.html