简体   繁体   中英

mysql query takes 13min to run

I have three tables, and i am joining them using the code below

  • orders has 30k rows
  • orders_details has over 100k rows
  • services has 4 rows

when I execute the script below in Fish Database.net , it takes over 13mins to run before displaying the result!!!

select 
  `o`.`created` AS `created`,
  sum(`o`.`total`) AS `total`,
  sum(`o`.`paid`) AS `paid`,
  `od`.`service_id` AS `service_id`,
  `s`.`name` AS `grp` 
from ((`orders` `o` 
  left join `orders_details` `od` on
    (
      (`od`.`order_id` = `o`.`id`)
    )) 
  left join `services` `s` on
    (
      (`s`.`id` = `od`.`service_id`)
    )) 
group by 
  `od`.`service_id`,
  `o`.`created`,
  `s`.`name` 
order by 
  `o`.`created`
  • all column names with id are integer primary key columns
  • created is a datetime column
  • total, paid are decimal(10,2) columns
  • name is a varchar (60) columns

Here is the explain result

EDITS

id  select_type table   type    possible_keys   key key_len ref rows    Extra

1   SIMPLE  o   ALL NULL    NULL    NULL    NULL    23558   Using temporary; Using filesort
1   SIMPLE  od  ALL NULL    NULL    NULL    NULL    40304   
1   SIMPLE  s   eq_ref  PRIMARY PRIMARY 4   mydb.od.service_id  1   

I can i improve/find the bottleneck ??

The use of (unuseful) nested () can degrading performance then try remove unseful ()
Be sure you have correct index on od.order_id, o.id , s.id , od.service_id

  select 
    o.created AS created,
    sum(o.total) AS total,
    sum(o.paid) AS paid,
    od.service_id AS service_id,
    s.name AS grp 
  from orders o 
    left join orders_details od on  od.order_id = o.id 
    left join services s on s.id = od.service_id 
  group by 
    od.service_id,
    o.created,
    s.name 
  order by 
    o.created

for a better reading i have removed also backtics .. you don't have resersved words od multi words column name so should not be needed)

There are steps to find bottlenecks in sql script.

  1. First of all,examine the execution plans and query statistics.
  2. Execution plan will tell you where is the bottleneck.
  3. Depending on the problem, create indexes and then again examine execution plan.
  4. Apply pagination when needed. Sending data in batches also can make difference.

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