无法在嵌套查询中处理字段

时间:2012-10-05 09:38:02

标签: sql oracle subquery

我有这样的疑问:

select d.r_object_id,

    (select max(max_date) from (

        SELECT max(sys_s.r_modify_date) AS max_date
        FROM kc_mission_s mis_s, dm_sysobject_s sys_s
        WHERE mis_s.r_object_id = sys_s.r_object_id AND mis_s.ka_document = d.r_object_id

        union all

        SELECT sys_s.r_modify_date AS max_date
        FROM dm_document_s doc_s left join dm_sysobject_s sys_s on doc_s.r_object_id = sys_s.r_object_id
        WHERE doc_s.r_object_id = d.r_object_id

    )) as maxx

from kc_document_s d

从上一个嵌套查询中看不到字段d.r_object_id。 如果中间查询将被删除,它将是可见的:

select d.r_object_id,

    (
        SELECT max(sys_s.r_modify_date) AS max_date
        FROM kc_mission_s mis_s, dm_sysobject_s sys_s
        WHERE mis_s.r_object_id = sys_s.r_object_id AND mis_s.ka_document = d.r_object_id

        union all

        SELECT sys_s.r_modify_date AS max_date
        FROM dm_document_s doc_s left join dm_sysobject_s sys_s on doc_s.r_object_id = sys_s.r_object_id
        WHERE doc_s.r_object_id = d.r_object_id

    ) as maxx

from kc_document_s d

但在这种情况下,我不允许选择多行。 我该怎么办?

2 个答案:

答案 0 :(得分:0)

如果继续从中级查询到最低级别查询的连接,并且还包括每个级别的连接列,那么它应该可以工作

select d.r_object_id,
    (select max(max_date) from (
        SELECT max(sys_s.r_modify_date) AS max_date,
        d.r_object_id
        FROM kc_mission_s mis_s, dm_sysobject_s sys_s
        WHERE mis_s.r_object_id = sys_s.r_object_id AND mis_s.ka_document = d.r_object_id

        union all

        SELECT sys_s.r_modify_date AS max_date,
        d.r_object_id
        FROM dm_document_s doc_s left join dm_sysobject_s sys_s on doc_s.r_object_id = sys_s.r_object_id
        WHERE doc_s.r_object_id = d.r_object_id
    ) sub_query
      where sub_query.r_object_id = d.r_object_id
    ) as maxx
from kc_document_s d

答案 1 :(得分:0)

试试这个

select d.r_object_id,
       greatest((select max(sys_s.r_modify_date) as max_date
          from kc_mission_s mis_s, dm_sysobject_s sys_s
         where mis_s.r_object_id = sys_s.r_object_id
           and mis_s.ka_document = d.r_object_id), 
        (select sys_s.r_modify_date as max_date
          from dm_document_s doc_s
          left join dm_sysobject_s sys_s
            on doc_s.r_object_id = sys_s.r_object_id
         where doc_s.r_object_id = d.r_object_id)
        ) as maxx
  from kc_document_s d