Performance and SQL Analysis

        The test found that one of our interfaces has performance problems. After analysis, a SQL in a SQLMAP has two levels of business logic, which are connected by OR, as shown below.

select * from table_name where a='111' and b='222' and c='333' or d = '444';

        There is about 100W of data in this table. Looking at the table creation statement, it is found that a, b, and c are the primary keys, and the d field is not indexed. So the first optimization I immediately thought of was to build an index on d.

1. Seek unique index

        And from the perspective of business logic, the d field will not be repeated, so a unique index is built for the d field, and the performance of the test pressure test is still not good.

 

2. Use union all to replace or

        Analysis of business, because it is to make repeated judgments, because from a business perspective, union all can be used to replace or, so modify the SQL as follows:

select * from table_name where a='111' and b='222' and c='333'
union all
select * from table_name where d = '444';

        Then do performance analysis to basically meet the business requirements.

 

3. Split the above SQL into two SQL statements

        Split the above SQL into the following two SQL statements:

select * from table_name where a='111' and b='222' and c='333';
select * from d = '444';

        Separate calls at the application layer, and then perform performance analysis, basically meet the business requirements.

 

4. SQL Analysis

1.explain select * from table_name where a='111' and b='222' and c='333' or d = '444';


2.explain select * from table_name where a='111' and b='222' and c='333' union all select * from table_name where d = '444';


3.explain select * from table_name where a='111' and b='222' and c='333';


4.explain select * from table_name where d = '444';

        From the point of view of SQL analysis, the primary key and unique index to find the required row in the table are const, which means that when MySQL optimizes a certain part of the query and converts it into a constant, these types of access are used.

        system is a special case of const type. When the query table has only one row, use system.

 

五.Impossible WHERE noticed after reading const tables分析

  Replace a non-existing primary key or unique index value, as shown in the following SQL:

explain select * from table_name where d = 'aaa';
explain select * from table_name where a='aaa' and b='bbb' and c='ccc';


        It is said that this is because MySQL first queries the index records, and then analyzes the effect.

 

Attachment: Knowledge Review

        explain的type显示的是访问类型,是较为重要的一个指标,结果值从好到坏依次是:system > const > eq_ref > ref > fulltext > ref_or_null > index_merge > unique_subquery > index_subquery > range > index > ALL

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326551035&siteId=291194637