SELECT COL1,
COL2,
COL3
FROM TABLE1,
TABLE2,
TABLE3,
TABLE4
WHERE TABLE1.KEY1 = TABLE2.KEY1
AND TABLE2.KEY = TABLE3.KEY
AND TABLE2.FILTER = 'Y'
AND TABLE3.FILTER = 'Y'
AND TABLE2.KEY = TABLE3.KEY
AND TABLE3.KEY = TABLE4.KEY
我有类似的查询,我需要进行修改,在表3中有一个日期列,我需要选择最高日值行进行加入。假设表3中有4行对连接感到满意,我需要从这4行中选出最高日期行以进行连接,然后显示结果。
希望问题很清楚。数据库oracle 10g
答案 0 :(得分:1)
尝试类似此查询的内容。
SELECT
COL1,
COL2,
COL3,
T33.*
FROM TABLE1
JOIN TABLE2 ON TABLE1.KEY1 = TABLE2.KEY1
JOIN TABLE4 ON TABLE2.KEY = TABLE4.KEY
JOIN
(
SELECT MAX(T.Day) as DT, T.KEY
FROM TABLE3 T
WHERE T.FILTER = 'Y'
GROUP BY T.KEY
) T3 on TABLE4.KEY = T3.KEY
JOIN TABLE3 T33 ON T3.KEY = T33.KEY AND T3.DT = T33.Day
WHERE
TABLE2.FILTER = 'Y'
主要思想是代替中
加入TABLE3
即可:
SELECT MAX(T.Day) as DT, T.KEY
FROM TABLE3 T
WHERE T.FILTER = 'Y'
GROUP BY T.KEY
为该表/记录集命名并加入其中。
然后您可以再次加入原始TABLE3
(请参阅T33
)
从TABLE3
中提取所有其他所需的列
T3
中没有出现。
我认为你可以解决其他问题。
答案 1 :(得分:0)
要最低限度地修改当前查询,您可以在WHERE
子句中添加条件
AND TABLE3.DATE = (SELECT MAX(DATE) FROM TABLE3 WHERE TABLE3.FILTER = 'Y')
虽然将来我建议使用显式JOINS。
SELECT COL1,
COL2,
COL3
FROM TABLE1
INNER JOIN TABLE2 ON TABLE1.KEY1 = TABLE2.KEY1
INNER JOIN TABLE3 ON TABLE2.KEY = TABLE3.KEY
INNER JOIN TABLE4 ON TABLE3.KEY = TABLE4.KEY
WHERE
TABLE2.FILTER = 'Y'
AND TABLE3.FILTER = 'Y'
AND TABLE3.DATE = (SELECT MAX(DATE) FROM TABLE3 WHERE TABLE3.FILTER = 'Y')