有没有办法在Oracle 11g SQL中为子查询提供别名?

时间:2010-06-16 23:35:45

标签: sql oracle subquery oracle11g table-alias

有没有办法在Oracle 11g中为子查询提供如下别名:

select * 
from
    (select client_ref_id, request from some_table where message_type = 1) abc,
    (select client_ref_id, response  from some_table where message_type = 2) defg
where
    abc.client_ref_id = def.client_ref_id;

否则有一种方法可以基于client_ref_id连接两个子查询。我意识到有一个自连接,但在数据库上我运行的自连接可能需要5分钟才能完成(在我运行的实际查询中有一些额外的逻辑,但我已确定自联接是什么导致问题)。各个子查询只需几秒钟即可完成。自联接查询类似于:

select st.request, st1.request
from
    some_table st, some_table st1
where 
    st.client_ref_id = st1.client_ref_id;

3 个答案:

答案 0 :(得分:20)

WITH abc as (select client_ref_id, request from some_table where message_type = 1)
select * 
from abc
    inner join 
    (select client_ref_id, response  from some_table where message_type = 2) defg
on   abc.client_ref_id = def.client_ref_id;

答案 1 :(得分:5)

我没有要测试的Oracle实例,但您发布的内容应该是有效的ANSI-89 JOIN语法。这是ANSI-92:

SELECT *
  FROM (SELECT client_ref_id, request 
          FROM SOME_TABLE 
         WHERE message_type = 1) abc
  JOIN (SELECT client_ref_id, request 
          FROM SOME_TABLE 
         WHERE message_type = 1) defg ON defg.client_ref_id = abc.client_ref_id

答案 2 :(得分:3)

您的查询应该没问题。

另一种选择是:

select abc.client_ref_id, abc.request, def.response
from   some_table abc,
       some_table def
where  abc.client_ref_id = def.client_ref_id
and    abc.message_type = 1
and    def.message_type = 2;

如果Oracle重新编写查询以便计划完全相同,我不会感到惊讶。