bachecubano bachecubano - 1 month ago 9
MySQL Question

MySQL: Optimizing a 300+ second query?

I have a classiffieds website and we got A LOT of new visitors this month.

The website simply exploded and started to deliver a "Can't connect with DB". I'm using codeigniter and this is the trace un Mysql Logs:

# Time: 160924 22:50:20
# Thread_id: 1914 Schema: erich33_asd QC_hit: No
# Query_time: 378.515875 Lock_time: 375.061742 Rows_sent: 75 Rows_examined: 152644
SET timestamp=1474771820;
SELECT `category`.`id` as `category_id`, `category`.`subcat` as `category_name`, `category`.`desc` as `category_desc`, `category`.`name` as `category_pretty_name`, `ads`.`id`, `ads`.`header`, `ads`.`price`, SUBSTR(ads.body, 1, 160) as body, `ads`.`sellfast`, `ads`.`foto1`, `ads`.`foto2`, `ads`.`foto3`, `ads`.`foto4`, `ads`.`foto5`, `ads`.`updated`, `ads`.`created`, `ads`.`hits`, `promo`.`promotype` as `promo_type`, `provinces`.`prov_name`, `supercategory`.`name` as `supercategory_name`, `supercategory`.`id` as `supercategory_id`
FROM `ads`
JOIN `category` ON `category`.`id` = `ads`.`subcat_id`
JOIN `supercategory` ON `supercategory`.`id` = `category`.`cat`
JOIN `provinces` ON `provinces`.`id` = `ads`.`province_id`
LEFT OUTER JOIN `promo` ON `promo`.`ads_id` = `ads`.`id`
WHERE `ads`.`subcat_id` = '22'
AND `recycle_bin` != 1
AND `hidden` =0
ORDER BY `promo_type` DESC, `updated` DESC
LIMIT 833, 75;


As you can see it took 378.515875 seconds to complete.

How would you optimize this query to take less time?

Answer

The problem was a bad index configuration in DB schema. Just added an index in ads.recycle_bin, ads.hidden and ads.subcat_id

Thanks!

Comments