简体   繁体   中英

How can I optimize this query, takes more than a min to execute

I have following query which take more than a minute to execute, how can I optimize it. Its slow because of order by o.id desc , if I remove it query executes it few ms.


select o.*, per.email, p.name
from order o 
inner join product p 
on o.product_id=p.id 
inner join person per 
on o.person_id=per.id 
order by o.id desc 
limit 100;

Following is the result of explain


1   SIMPLE  p   index   PRIMARY FK2EFC6C1E5DE2FC    8   NULL    6886    Using index; Using temporary; Using filesort
1   SIMPLE  o   ref FK67E9050121C383DB,FK67E90501FC44A17C   FK67E90501FC44A17C  8   dev.p.id    58  
1   SIMPLE  per eq_ref  PRIMARY PRIMARY 8   dev.o.person_id 1   Using index

All the tables are InnoDB and joins are on Primary and Foreign keys. Other than that indexes are on email column in Person and status column in Order

Number of records in each table

Person : 1,300,000 Product: 7,000 Order : 70,000

The planner, most probably, is not using the limit hint to eliminate rows from order table before the join. So the server has to do the join for all rows and then return just a few.

Try this:

select o.* from
(select * order order by id desc limit 100) o
inner join product p 
on o.product_id=p.id 
inner join person per 
on o.person_id=per.id 
order by o.id desc limit 100;

EDIT: This will work only if there is a constraint guaranteeing that corresponding rows are present in Product and Person tables.

yes, i understand your question, in this case first of all, save your query in .sql file. you can use sql server utility called "Database Engine Tuning Advisor" in Tools menu of the Sql Server Management studio.

first open sql server and go to tools and select option "Database Engine Tuning Advisor". then select the file you stored previously. now tick mark your database which you are using and table which is used in query and then click on Start Analysis in main menu. it show you possible index and statestics to create now to apply this recommandation to your query, go to action manu and select "Apply Recommandation" that will create indexes and statestics on on your table and reduce the execution time of query.

Increase the value of this variabled and restart MySQL server read_rnd_buffer_size setting the variable to a large value can improve ORDER BY performance by a lot.

Also you can refer http://www.mysqlperformanceblog.com/2007/07/24/what-exactly-is-read_rnd_buffer_size/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM