您能否帮我优化此查询:
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)
)
我想逃离EXISTS
或NOT EXISTS
,只留下一个。
答案 0 :(得分: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
条件移至条件聚合,如下所示:
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
在您的问题中,您没有提供足够的信息来确切了解您的需求,但上述两条建议已接近。