简体   繁体   中英

mysql query is taking too much time to execute

Hello everyone I am working on phpmyadmin database. Whenever I try to execute query it takes too much time more than 10 mins to show results. Is there any way to speed it up. please response.

The query is

SELECT ib.*, b.brand_name, m.model_name,
       s.id as sale_id, br.branch_code,br.branch_name,r.rentry_date,r.id as rid
  from in_book ib 
  left join brand b on ib.brand_id=b.id
  left join model m on ib.vehicle_id=m.id
  left join re_entry r on r.in_book_id=ib.id
  left join sale s on ib.id=s.in_book_id
  left join branch br on ib.branch_id=br.id
 where ib.id !=''
   and ib.branch_id='65'
 group by ib.id
 order by r.id ASC,
       count(r.in_book_id) DESC ,
       ib.purchaes_date ASC,
       ib.id ASC

there are almost 7 tables

make sure you got an index on every key you use to join the tables.

from http://dev.mysql.com/doc/refman/5.5/en/optimization-indexes.html :

The best way to improve the performance of SELECT operations is to create indexes on one or more of the columns that are tested in the query. The index entries act like pointers to the table rows, allowing the query to quickly determine which rows match a condition in the WHERE clause, and retrieve the other column values for those rows. All MySQL data types can be indexed.

.. this of course also applies to the JOIN conditions.

You don't list any such indexes, however, I would start with the following suggested indexes

table      index
in_book    ( branch_id, id, brand_id, vehicle_id )
brand      ( id, brand_name )
model      ( id, model_name )
re_entry   ( in_book_id, id, reentry_date )
sale       ( in_book_id, id )
branch     ( id )

Also, with MySQL, you can use a special keyword "STRAIGHT_JOIN" which tells the engine to query in the order you have selected the tables... Although you are doing LEFT JOINs, I don't think it will matter as it appears the secondary tables are all lookup type of tables and in_book is your primary. But as just a try it would be..

SELECT STRAIGHT_JOIN  (...rest of query...)

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