I have a MySQL query theat takes a long time to run.
Here is my query:
SELECT DISTINCT *,ROUND((total_gross_profit- (payment_processor_holdout+payment_processor_fee)-(affiliate_commission_base+affiliate_commission_markup)),2) as net_profit FROM (SELECT O.id as oid
,M.last_name
,M.first_name
,D.product_name
,D.dosage_name
,O.date
,O.delivery
,O.aff_id
,IFNULL(O.product_total,0) as product_price
,IFNULL(O.discount_amount,0) as purchase_discount
,IFNULL((O.product_total - O.discount_amount),0) as net_sales
,IFNULL(ROUND((O.total - O.product_total),2),0) as shipping_fee
,IFNULL(ROUND(((O.product_total - O.discount_amount) - (O.total - O.product_total)),2),0) as gross_sales
,IFNULL(P.unit_cost,0) as product_unit_cost
,IFNULL((P.unit_cost * D.dosage_name),0) as costofgoods
,aset.setting_value as shipping_cost
,IFNULL(ROUND(((O.product_total - O.discount_amount) - (O.total - O.product_total) - (P.unit_cost * D.dosage_name)),2),0) as goods_gross_profit
,IFNULL(ROUND(((O.total - O.product_total) - aset.setting_value),2),0) as shipping_gross_profit
,(IFNULL(ROUND(((O.product_total - O.discount_amount) - (O.total - O.product_total) - (P.unit_cost * D.dosage_name)),2),0)+ IFNULL(ROUND(((O.total - O.product_total) - aset.setting_value),2),0)) as total_gross_profit
,IFNULL(ROUND(IF(E.category_id IN (95,96,97,98,99),E.price*.25,E.price*.40),2),0) AS affiliate_commission_base
,IFNULL(ROUND((F.price_markup*.50),2),0) AS affiliate_commission_markup
,IFNULL((SELECT ppf.value FROM `aff_settings` ap
LEFT JOIN `payment_processor_fee` ppf
ON ap.setting_value=ppf.payment_processor_type
WHERE ap.setting_name='payment_processor'),0) as payment_processor_fee
,IFNULL(ROUND(((SELECT pph.value FROM `aff_settings` ap
LEFT JOIN `payment_processor_holdout` pph
ON ap.setting_value=pph.payment_processor_type
WHERE ap.setting_name='payment_processor')* O.total),2),0) as payment_processor_holdout
FROM `order` as O
LEFT JOIN `order_detail` as D
ON O.id = D.order_id
LEFT JOIN `members` as M
ON M.id = O.buyer_id
LEFT JOIN `products` as P
ON P.generic_name = D.product_name
LEFT JOIN `aff_settings` as aset
ON aset.setting_name = O.delivery
LEFT JOIN `aff_order_details` as E
ON D.id = E.order_detail_ref_id
LEFT JOIN `aff_group_product_prices` as F
ON F.aff_id = O.aff_id
AND F.product_id =P.Id
AND F.dosage_id=D.dosage_name
ORDER BY M.last_name) AS x
I have a lot of joined tables. Is there any way to make the query run faster? If so, how?
Thank you for your help.
Run EXPLAIN PLAN on that query. You'll probably see TABLE SCAN, which means you'll have to add indexes and/or rewrite the 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.