IBM Db2 Sql 查询优化

IBM Db2 Sql query optimization

我有这个查询:

select DBSAITE.MITEM, DBSAITE.MPDSC, DBSAITE.MUTMS, MVSACPE.COSTUN,  PCSACST.CSTTYAPP, 
SUM(PCSACST.CSTBURD1 + PCSACST.CSTBURD2 + PCSACST.CSTLABOR + 
PCSACST.CSTMAT + PCSACST.CSTSETUP + PCSACST.CSTEXTRN) as COSTO_STD 
from MVSACPE, PCSACST, DBSAITE
WHERE PCSACST.CSTCOSC = MVSACPE.CODSOC
AND PCSACST.CSTITEM = MVSACPE.CODITM
AND MVSACPE.CODITM = DBSAITE.MITEM
AND DBSAITE.MCOSC = 'GRS'
AND MVSACPE.CODSOC = 'GRS23'
AND MVSACPE.DTPERI = '201512'
AND MVSACPE.CODMAG = 'ALL'
AND MVSACPE.CODCOS = 'MPR' 
AND PCSACST.CSTDATE = '20150630'
AND PCSACST.CSTTYPE = 'SG'
GROUP BY DBSAITE.MITEM, DBSAITE.MPDSC, DBSAITE.MUTMS, MVSACPE.COSTUN,PCSACST.CSTTYAPP

我想以某种方式优化查询,因为连接处理数十万条记录并且非常慢(3 分钟)。

有什么建议吗?

首先,使用显式 JOIN 语法重写查询。如果不出意外,这会让您更容易看到要做什么:

select DBSAITE.MITEM, DBSAITE.MPDSC, DBSAITE.MUTMS, MVSACPE.COSTUN,  PCSACST.CSTTYAPP, 
SUM(PCSACST.CSTBURD1 + PCSACST.CSTBURD2 + PCSACST.CSTLABOR + 
PCSACST.CSTMAT + PCSACST.CSTSETUP + PCSACST.CSTEXTRN) as COSTO_STD 
from MVSACPE JOIN
     PCSACST
     ON PCSACST.CSTCOSC = MVSACPE.CODSOC AND
        PCSACST.CSTITEM = MVSACPE.CODITM JOIN
     DBSAITE
     ON MVSACPE.CODITM = DBSAITE.MITEM
WHERE DBSAITE.MCOSC = 'GRS' AND
      MVSACPE.CODSOC = 'GRS23' AND
      MVSACPE.DTPERI = '201512' AND
      MVSACPE.CODMAG = 'ALL' AND
      MVSACPE.CODCOS = 'MPR' AND
      PCSACST.CSTDATE = '20150630' AND
      PCSACST.CSTTYPE = 'SG'
GROUP BY DBSAITE.MITEM, DBSAITE.MPDSC, DBSAITE.MUTMS, MVSACPE.COSTUN,PCSACST.CSTTYAPP;

索引可能有助于查询。目前尚不清楚哪些条件最具选择性。缺乏其他信息,一个好的起点是这些:

- `MVSACPE(CODSOC, DTPERI, CODMAG, CODCOS, CODITM)`
- `PCSACST(CSTCOSC, CSTITEM, CSTDATE, CSTTYPE)`
- `DBSAITE(MITEM, MCOSC)`