Oracle - 如何编写具有多个外连接和连接的查询到ansi sql中的日期

时间:2015-02-17 12:16:37

标签: sql oracle outer-join

我正在尝试使用外连接在ansi(sql 92)sql中编写以下查询:

select *
from   ota_delegate_bookings     odb,
       ota_events                oe,   -- aka Class
       per_all_assignments_f     paaf
where  oe.event_id = odb.event_id
and    paaf.person_id (+) = odb.delegate_person_id
and    paaf.assignment_type (+) in ('E', 'C')
and    paaf.primary_flag (+) = 'Y' 
and    oe.course_start_date between paaf.effective_start_date (+) and paaf.effective_end_date (+)

我遇到了可怕的ORA-01417: a table may be outer joined to at most one other table错误。我想知道较新的ansi sql外连接语法是否没有外部连接到多个表的限制;但我不知道如何把它写成ansi sql。你如何处理多个连接以及如何在两个连接之间使用?

1 个答案:

答案 0 :(得分:2)

你有一个右连接和左连接的组合,这就是导致关于一个表外部连接到最多另一个表的错误的原因。表格per_all_assignments_f外部加入了ota_eventsota_delegate_bookings。我不知道这个限制是否也适用于ANSI SQL连接;我的建议是使用子查询或CTE(我不确定连接是否有意义)。

(另外,我要问,你真的需要SELECT *吗?)

WITH ota AS (
    SELECT * FROM ota_delegate_bookings odb
     INNER JOIN ota_events oe
        ON odb.event_id = oe.event_id
)
SELECT * FROM ota LEFT JOIN per_all_assignments_f paaf
    ON ota.delegate_person_id = paaf.person_id
   AND ota.course_start_date BETWEEN paaf.effective_start_date AND paaf.effective_end_date
   AND paaf.assignment_type IN ('E', 'C')
   AND paaf.primary_flag = 'Y';

这也可以使用子查询编写:

SELECT * FROM (
    SELECT * FROM ota_delegate_bookings odb
     INNER JOIN ota_events oe
        ON odb.event_id = oe.event_id
) ota LEFT JOIN per_all_assignments_f paaf
    ON ota.delegate_person_id = paaf.person_id
   AND ota.course_start_date BETWEEN paaf.effective_start_date AND paaf.effective_end_date
   AND paaf.assignment_type IN ('E', 'C')
   AND paaf.primary_flag = 'Y';