我需要一个MySQL查询进行优化
我有一个在MySQL数据库上运行的查询,速度非常慢 我是否可以优化以下内容我需要一个MySQL查询进行优化,mysql,select,query-optimization,Mysql,Select,Query Optimization,我有一个在MySQL数据库上运行的查询,速度非常慢 我是否可以优化以下内容 SELECT mcm.merchant_name, ( ( Sum(ot.price) + Sum(ot.handling_charges) + Sum(ot.sales_tax_recd) + Sum(ot.shipping_cost) - Sum(ot.sales_tax_payable) ) - Sum(im.break_even_cost) ) AS PL, ot
SELECT mcm.merchant_name,
( ( Sum(ot.price) + Sum(ot.handling_charges)
+ Sum(ot.sales_tax_recd)
+ Sum(ot.shipping_cost) - Sum(ot.sales_tax_payable) ) -
Sum(im.break_even_cost) ) AS PL,
ot.merchant_id
FROM order_table ot,
item_master im,
merchant_master mcm
WHERE ot.item_id = im.item_id
AND ot.merchant_id = mcm.merchant_id
GROUP BY mcm.merchant_name
ORDER BY pl DESC
LIMIT 0, 10;
执行上述查询需要200多秒
解释结果:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE ot ALL "merchant_id,item_id" NULL NULL NULL 507910 "Using temporary; Using filesort"
1 SIMPLE mcm eq_ref "PRIMARY,merchant_id" PRIMARY 4 stores.ot.merchant_id 1
1 SIMPLE im eq_ref "PRIMARY,item_id" PRIMARY 4 stores.ot.item_id 1
另外,当我运行EXPLAIN EXTENDEDuse plan来找出花费这么长时间的原因,然后可能创建一些索引或更改代码时,出现了错误-1003
更新
基于此,请确保您在
merchant\u id,item\u id
上的order\u表上有一个复合索引,您应该使用“EXPLAIN EXTENDED”前缀(EXPLAIN EXTENDED SELECT mcm.merchant\u name,…)发布此查询的输出。这更像是一个架构设计问题,查询本身并不过分。id选择类型表类型可能的密钥密钥长度参考行额外1个简单otall“merchant\u id,item\u id”NULL NULL NULL NULL 507910使用临时;使用文件排序“1 SIMPLE mcm eq\u ref”PRIMARY,merchant\u id”PRIMARY 4 stores.ot.merchant\u id 1 1简单im eq\u ref“PRIMARY,item_id”PRIMARY 4 stores.ot.item_id 1
@user2992030请将其添加到您的帖子中,并使其可读性看起来商户id
和订单表中的item_id
id选择类型表类型可能的键参考行额外1个简单的otall”商户id,商品id“NULL 507910”使用临时标识;使用文件排序“1简单mcm均衡器参考”主,商户id“主4个门店。ot.商户id 1 1简单im均衡器参考”主,物料id“主4个门店。ot.物料id 1
我已将解释结果添加到问题中