2

我有一个 Oracle 11 SQL 查询,我从 4 个表中提取数据,这些表都由一个 ID 连接。连接到第一个表的 3 个表都有一个 ACTIVE_IND 值,该值需要为“Y”和一个生效日期 (EFF_DATE),我需要每个表的最大生效日期记录。

我有一个可以在这里工作的查询,但想知道是否有更优化/有效/高效的编写方式,因为它看起来有点慢。我目前使用的看起来像这样:

SELECT DISTINCT A.TABLE1_ID,
                A.TABLE1_COL1,
                B.TABLE2_COL2,
                C.TABLE3_COL3,
                D.TABLE4_COL4
FROM TABLE1 A,
     TABLE2 B,
     TABLE3 C,
     TABLE4 D
WHERE B.TABLE2_ID = A.TABLE1_ID
  AND B.TABLE2_ACTIVE_IND = 'Y'
  AND B.TABLE2_EFF_DATE =
    (SELECT MAX (B2.TABLE2_EFF_DATE)
     FROM TABLE2 B2
     WHERE B2.TABLE2_ID = B.TABLE2_ID
       AND B2.TABLE2_ACTIVE_IND = 'Y')
  AND C.TABLE3_ID = A.TABLE1_ID
  AND C.TABLE3_ACTIVE_IND = 'Y'
  AND C.TABLE3_EFF_DATE =
    (SELECT MAX (C2.TABLE3_EFF_DATE)
     FROM TABLE3 C2
     WHERE C2.TABLE3_ID = C.TABLE3_ID
       AND C2.TABLE3_ACTIVE_IND = 'Y')
  AND D.TABLE4_ID = A.TABLE1_ID
  AND D.TABLE4_ACTIVE_IND = 'Y'
  AND D.TABLE4_EFF_DATE =
    (SELECT MAX (D2.TABLE4_EFF_DATE)
     FROM TABLE4 D2
     WHERE D2.TABLE4_ID = D.TABLE4_ID
       AND D2.TABLE4_ACTIVE_IND = 'Y')
ORDER BY A.TABLE1_ID;
4

1 回答 1

2

尝试:

SELECT DISTINCT A.TABLE1_ID,
                A.TABLE1_COL1,
                B.TABLE2_COL2,
                C.TABLE3_COL3,
                D.TABLE4_COL4
FROM TABLE1 A
JOIN (SELECT T2.*, 
             RANK() OVER (PARTITION BY TABLE2_ID ORDER BY TABLE2_EFF_DATE DESC) RN
      FROM TABLE2 T2
      WHERE TABLE2_ACTIVE_IND = 'Y') B ON B.TABLE2_ID = A.TABLE1_ID AND B.RN=1
JOIN (SELECT T3.*, 
             RANK() OVER (PARTITION BY TABLE3_ID ORDER BY TABLE3_EFF_DATE DESC) RN
      FROM TABLE3 T3
      WHERE TABLE3_ACTIVE_IND = 'Y') C ON C.TABLE3_ID = A.TABLE1_ID AND C.RN=1
JOIN (SELECT T4.*, 
             RANK() OVER (PARTITION BY TABLE4_ID ORDER BY TABLE4_EFF_DATE DESC) RN
      FROM TABLE4 T4
      WHERE TABLE4_ACTIVE_IND = 'Y') D ON D.TABLE4_ID = A.TABLE1_ID AND D.RN=1
ORDER BY A.TABLE1_ID;
于 2013-03-11T17:36:21.590 回答