MySQL查询需要一段时间才能运行

时间:2012-05-24 14:21:49

标签: mysql performance

我有一个MySQL查询,需要很长时间才能运行。

这是我的问题:

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

我有很多联合表。有没有办法让查询运行得更快?如果是这样,怎么样?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在该查询上运行EXPLAIN PLAN。您可能会看到TABLE SCAN,这意味着您必须添加索引和/或重写查询。