简体   繁体   中英

How can make mysql query with left join more faster

I am creating a module in Magento2 "Who Bought This Also Bought" and I have very big database and my MySQL query taking too much time to execute just for one product please let me know any idea to make my query faster. I am using MySQL Ver 8.0.29-21 for Linux on x86_64 and PHP 7.4.28

SELECT `main_table`.`product_id`,
       (SUM(`main_table`.`product_id`) / `main_table`.`product_id`) AS `frequency`,
       `sub_table`.`order_id`,
        `sub_table`.`product_id`
FROM `sales_order_item` AS `main_table`
LEFT JOIN `sales_order_item` AS `sub_table` ON `main_table`.`order_id` = `sub_table`.`order_id` AND `main_table`.`product_id` != `sub_table`.`product_id`
WHERE (`main_table`.`product_id` = 1) 
AND (`sub_table`.`product_type` NOT IN ('configurable', 'bundle')) 
AND (`sub_table`.`parent_item_id` IS NULL)
GROUP BY `sub_table`.`product_id`
ORDER BY `frequency` DESC

In Magento 2, For speed in the catalog using a Flat table and category, for your custom module create a resource model in your custom mode, that will speed and optimize your Mysql join based on your requirement.

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