优化子查询/更好的编写查询的方法

时间:2018-01-24 19:53:59

标签: sql

有没有办法优化以下查询?

{{1}}

由于

3 个答案:

答案 0 :(得分:0)

这是一个更简单的版本:

SELECT 
 IRN, COMPLETION_DATE, FUNDS_MOP, SRC_IND, FUNDS_LOCAL_CURR, FUNDS_ORIG_CURR, FUNDS_LOCAL_AMT, FUNDS_ORIG_AMT, OBIREF_1, OBIREF_2, OBIREF_3, OBIREF_4, BBIREF_1, BBIREF_2, BBIREF_3, BBIREF_4, BBIREF_5, BBIREF_6
 FROM
MANTAS_STG.NY_EGIFTS_TRANS_STG
WHERE NY_EGIFTS_TRANS_STG.SRC_IND!='BK1' AND NY_EGIFTS_TRANS_STG.SRC_IND!='ADV' AND NY_EGIFTS_TRANS_STG.PROC_FLAG=1
AND (LTRIM(RTRIM(ORG_ID)) not IN('398601', '2296','399509','200111','302333','044401') OR LTRIM(RTRIM(ORG_ID)) is null)
AND (LTRIM(RTRIM(OGB_ID)) NOT IN('398601', '2296','399509','200111','302333','044401') OR  LTRIM(RTRIM(OGB_ID)) is null)
AND (DR_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(DR_ID)) is null)
AND (CR_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(CR_ID)) is null)
AND (INST_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(INST_ID)) is null)
AND (BNF_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(BNF_ID)) is null)
AND (IBK_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(IBK_ID)) is null)
AND (BBK_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(BBK_ID)) is null)
AND (SND_BANK_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(SND_BANK_ID)) is null)
AND (RCV_BANK_ID NOT IN('398601', '2296','399509','200111','302333','044401')OR LTRIM(RTRIM(SND_BANK_ID)) is null)

答案 1 :(得分:0)

只需使用AND和适当的逻辑。没有必要使用嵌套的子查询。

SELECT ets.*
FROM MANTAS_STG.NY_EGIFTS_TRANS_STG ets
WHERE ets.SRC_IND NOT IN ('BK1', 'ADV') AND ets.PROC_FLAG = 1 AND
      (LTRIM(RTRIM(ets.ORG_ID)) not IN ('398601', '2296', '399509', '200111', '302333', '044401') OR LTRIM(RTRIM(ets.ORG_ID)) is null) AND
      (LTRIM(RTRIM(B.OGB_ID)) NOT IN ('398601', '2296', '399509', '200111', '302333', '044401') OR  LTRIM(RTRIM(ets.OGB_ID)) is null) AND
      (ets.DR_ID NOT IN ('398601', '2296', '399509', '200111', '302333', '044401') OR LTRIM(RTRIM(ets.DR_ID)) is null) AND . . .

答案 2 :(得分:0)

我认为以下内容将更易于维护。作为概念的证明,这里是an sqlfiddle。您没有标记数据库,因此这是特定于Oracle的(使用from dual),但您可以轻松地重写以使用任何数据库。

SELECT MANTAS_STG.NY_EGIFTS_TRANS_STG.*
FROM MANTAS_STG.NY_EGIFTS_TRANS_STG left outer join
(
SELECT '398601' as num FROM dual
union all
SELECT '2296' FROM dual
union all
SELECT '399509' FROM dual
union all
SELECT '200111' FROM dual
union all
SELECT '302333' FROM dual
union all
SELECT '044401' FROM dual
) a
on
  LTRIM(RTRIM(ORG_ID)) = a.num
  OR LTRIM(RTRIM(OGB_ID)) = a.num
  OR DR_ID = a.num
  OR CR_ID = a.num
  OR INST_ID = a.num
  OR BNF_ID = a.num
  OR IBK_ID = a.num
  OR BBK_ID = a.num
  OR SND_BANK_ID = a.num
  OR RCV_BANK_ID = a.num
WHERE 
  NY_EGIFTS_TRANS_STG.SRC_IND!='BK1' AND NY_EGIFTS_TRANS_STG.SRC_IND!='ADV' AND NY_EGIFTS_TRANS_STG.PROC_FLAG=1
  AND a.num is null