High-performance MYSQL (study notes) - query performance optimization 3

Limitations of MySQL Query Optimizer

correlated subqueries

MySQL's correlated subqueries are bad, especially where in() is written, such as select * from sakila.filmwhere film_id in(select film_id from sakila.film_actor where actor_id = 1);

Mysql will not execute the subquery first, and then execute the in operation. Mysql will rewrite the above statement as:

Select * from sakila.film whereexists(select * from sakila.film_actor where actor_id = 1 and film_actor.film_id= film.film_id);

We can rewrite it as follows: select film.* from sakila.film innerjoin sakila.film_actor using(film_id) where actor_id = 1

How to make good use of correlated subqueries

Limitations of UNION

If you want each clause of union to take only part of the result set according to LIMIT, or if you want to sort the result set before merging the result set, you need to use these clauses in each clause of the union, for example (select first, from sakila. actor order by first) union all(select firstfrom sakila.customer order by first)limit 20;

This query will put 200 records in actor and 500 records in customer into a temporary table, and then query 20 records from the temporary table. You can reduce the data in the temporary table by adding a LIMIT 20 to each of the two subqueries of union (select first, from sakila.actor order by first limit 20) unionall(select first from sakila.customer order by first limit 20) limit 20;

Index merge optimization

When the where clause contains multiple complex conditions, MySQL can access multiple indexes of a single table to merge and cross filter to locate the rows that need to be queried.

Optimize specific types of queries

Optimizing COUNT() queries

Count() is a special function that has two very different functions. It can count the number of column values ​​and the number of rows. When counting column values, the column values ​​are required to be non-null. Another function is to count the results. The number of rows in the set, count(*) ignores all columns and counts the number of rows directly. A column is specified in parentheses but you want to count the number of rows in the result set. If you want to know the number of rows in the result set, count(*) is best.

simple optimization

You can write this query like this:

Select count(*) from world.city where id>5; through show status, we know that a large amount of data needs to be queried. If you reverse the condition, first find the number of cities with id<5, and then use count(*) to subtract it. Reduce the number of scanned rows to less than 5 rows: select (select count(*) from world.city)-count(*) from world.citywhere id<=5;

 


Guess you like

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