为什么这个查询需要很长时间才能执行

时间:2012-08-21 08:54:17

标签: mysql query-optimization

我有三张桌子

  • glSalesJournal
  • HMISAdd
  • HMISMain

现在我要做的是添加glSalesJournal amt和HMISAdd amt,同时分组各种Fields并将结果插入glSalesJournal

glSalesJournal包含633173条记录

HMISAdd包含4193条记录

HMISAdd和glSalesJournal包含相同的列

  • LOC
  • glAcct
  • glSubAcct
  • batchNbr
  • contractNbr
  • AMT

我在表中添加了索引,结果仍然相同。

这是我的代码:

INSERT INTO hmismain
            (loc,
             glacct,
             subacct,
             batchnbr,
             contractnbr,
             amt)
SELECT glsalesjournal.loc,
       glsalesjournal.glacct,
       glsalesjournal.glsubacct,
       ( glsalesjournal.amt + hmisadd.amt ) AS sumAmt,
       glsalesjournal.batchnbr,
       glsalesjournal.salescontnbr
FROM   glsalesjournal
       LEFT OUTER JOIN hmisadd
                    ON ( glsalesjournal.loc = hmisadd.loc
                         AND glsalesjournal.glacct = hmisadd.glacct
                         AND glsalesjournal.glsubacct = hmisadd.subacct
                         AND glsalesjournal.batchnbr = hmisadd.batchnbr
                         AND glsalesjournal.salescontnbr = hmisadd.contractnbr )
GROUP  BY glsalesjournal.loc,
          hmisadd.loc,
          glsalesjournal.glacct,
          hmisadd.glacct,
          glsalesjournal.glsubacct,
          hmisadd.subacct,
          glsalesjournal.batchnbr,
          hmisadd.batchnbr,
          glsalesjournal.salescontnbr,
          hmisadd.contractnbr

脚本执行的时间超过2小时。即使我将记录限制为100,所用的时间也是一样的。

有人可以指导我如何优化脚本。

由于

2 个答案:

答案 0 :(得分:2)

1)看起来这是一次性查询,我在这里是否正确?如果不是,每次都将相同的数据插入到hmismain表中 2)您正在对两个单独表格中的字段进行分组,因此没有任何索引数量可以帮助您。 ONLY 索引将有助于以相同方式链接这两个表的视图的索引。

进一步说明:
有什么意义

      GROUP  BY glsalesjournal.loc,
      hmisadd.loc,
      glsalesjournal.glacct,
      hmisadd.glacct,
      glsalesjournal.glsubacct,
      hmisadd.subacct,
      glsalesjournal.batchnbr,
      hmisadd.batchnbr,
      glsalesjournal.salescontnbr,
      hmisadd.contractnbr

您按两次相同的字段对数据进行分组 glsalesjournal.loc, hmisadd.loc
glsalesjournal.glacct, hmisadd.glacct,
...

从GROUP BY中删除重复项,它应该快速运行

答案 1 :(得分:0)

您是否在此字段中添加了索引:

glSalesJournal.loc
glSalesJournal.glAcct
glSalesJournal.glSubAcct
glSalesJournal.batchNbr
glSalesJournal.salesContNbr
HMISAdd.Loc
HMISAdd.GlAcct
HMISAdd.SubAcct
HMISAdd.batchNbr 
HMISAdd.contractNbr

如果此字段未编入索引,则会对每个记录执行完整扫描,从而导致性能降低。

<强> MySQL Create Index Syntax