2015-10-14 58 views
-2

你能幫我優化這個查詢:能不能幫我優化SQL查詢DB2

select distinct PUBLSEQ from PUBLCOVER P 
      WHERE EXISTS 
      (SELECT * FROM PUBLCOVER A, COVERAREA B, PRODCODEDICT C 
      WHERE A.PUBLSEQ = P.PUBLSEQ 
      AND A.COVER_STATUS = 'Y' 
      AND A.COVAREA = B.COVAREA 
      AND B.COVAREA_PRODCODE IS NOT NULL 
      AND B.COVAREA_PRODCODE = C.PRODCODE 
      AND C.STATUS = 'A' 
      AND A.COVAREA = 1823 
      ) 
      AND NOT EXISTS 
      (SELECT * FROM PUBLCOVER A, COVERAREA B, PRODCODEDICT C 
      WHERE A.PUBLSEQ = P.PUBLSEQ 
      AND A.COVER_STATUS = 'Y' 
      AND A.COVAREA = B.COVAREA 
      AND B.COVAREA_PRODCODE IS NOT NULL 
      AND B.COVAREA_PRODCODE = C.PRODCODE 
      AND C.STATUS = 'A' 
      AND A.COVAREA NOT IN (1823, 34) 
      ) 

我想從EXISTSNOT EXISTS逃跑,只留下一個。

+1

您要求A.COVAREA = 1823,也不是1823或34.與A.COVAREA = 1823和(1823或34)不一樣。這與1823年一樣?換句話說,第二個EXISTS是否真的做了什麼? –

+0

@MichaelY。大概有一個給定值爲'PUBLSEQ'的多條記錄,所以'EXISTS'確保至少有一個匹配項具有'1823'的'COVAREA'值,'NOT EXISTS'確保所有匹配項都是'1823'或'34'。或者,我只是累了。 –

+0

您的查詢實際上是否返回除1823之外的任何內容? –

回答

0

你應該能夠同時消除和簡單的HAVING子句中使用條件集合體,是這樣的:

SELECT A.PUBLSEQ 
FROM PUBLCOVER A 
    JOIN COVERAREA B 
    ON A.COVAREA = B.COVAREA 
    JOIN PRODCODEDICT C 
    ON B.COVAREA_PRODCODE = C.PRODCODE 
WHERE A.COVER_STATUS = 'Y' 
    AND B.COVAREA_PRODCODE IS NOT NULL 
    AND C.STATUS = 'A' 
GROUP BY A.PUBLSEQ 
HAVING MAX(CASE WHEN A.COVAREA NOT IN (1823, 34) THEN 1 ELSE 0 END) = 0 
    AND MAX(CASE WHEN A.COVAREA = 1823 THEN 1 ELSE 0 END) = 1 

可能需要移動WHERE標準條件骨料(S),像這樣:

SELECT A.PUBLSEQ 
FROM PUBLCOVER A 
    JOIN COVERAREA B 
    ON A.COVAREA = B.COVAREA 
    JOIN PRODCODEDICT C 
    ON B.COVAREA_PRODCODE = C.PRODCODE 
GROUP BY A.PUBLSEQ 
HAVING MAX(CASE WHEN A.COVAREA NOT IN (1823, 34) 
       AND A.COVER_STATUS = 'Y' 
       AND B.COVAREA_PRODCODE IS NOT NULL 
       AND C.STATUS = 'A' THEN 1 
       ELSE 0 
      END) = 0 
    AND MAX(CASE WHEN A.COVAREA = 1823 AND A.COVER_STATUS = 'Y' 
       AND B.COVAREA_PRODCODE IS NOT NULL 
       AND C.STATUS = 'A' 
       THEN 1 ELSE 0 
      END) = 1 

您尚未在您的問題中提供足夠的信息以確切知道您需要什麼,但上述兩個建議都很接近。

+0

它返回不同的結果。這與我的查詢不一樣 – Telal

+0

@Telal它返回的是什麼錯誤?我猜你需要將一些'WHERE'條件移入條件條件,但是你的問題中沒有足夠的信息要知道。另外,我在剛剛刪除的「WHERE」中有一條錯誤行,但它不應該在那裏運行。 –

+0

它只是返回不同的A.PUBLSEQ。結果不正確 – Telal