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
limithint 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:
EDIT: This will work only if there is a constraint guaranteeing that corresponding rows are present in Product and Person tables.