【问题标题】:I need a MySQL query to be optimized我需要优化 MySQL 查询
【发布时间】:2013-12-06 06:24:41
【问题描述】:

我有一个在 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.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 EXTENDED 时出现 Error-1003

【问题讨论】:

  • 您应该使用“EXPLAIN EXTENDED”前缀发布此查询的输出(EXPLAIN EXTENDED SELECT mcm.merchant_name,...)
  • 这往往是一个架构设计问题,它本身的查询并不过分。
  • 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
  • @user2992030 请将其添加到您的帖子中并使其可读
  • order_table 中的merchant_iditem_id 上似乎没有索引。

标签: mysql select query-optimization


【解决方案1】:

使用mysql explain plan 找出为什么需要这么长时间,然后可能会创建一些索引或更改您的代码。

更新 基于此,确保您在 merchant_id,item_id 上的 order_table 上有一个复合索引

【讨论】:

  • 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
  • 我在问题中添加了解释结果
猜你喜欢
  • 2016-02-02
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 2013-11-18
  • 2011-08-05
  • 1970-01-01
相关资源
最近更新 更多