暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 在查询中重复使用表别名

ASKTOM 2021-02-02
592

问题描述

当使用相同的表别名来引用联接列表中的表或视图以及 “与” 视图时,优先考虑前者。
这是意料之中的吗?如果是这样,为什么?

示例:
=

with t1 as (select 'DUMMY' X from dual) 
select t2.*
  from bibtest t1,
       bibtest_2 t2 
 where t1.a = t2.a;
复制



链接中还提供了其他详细信息。

请检查和帮助。
谢谢。

专家解答

在编写查询时,可以使用与其他架构对象名称匹配的别名:

create table t as 
  select level c1 from dual
  connect by level <= 5;
  
create or replace view vw as 
  select count(*) c from t;
  
select vw.* from t vw;

C1   
    1 
    2 
    3 
    4 
    5 

select * from vw;

C   
   5 
复制


在上面的第一个查询中,表别名与我们创建的视图的名称匹配。数据库将此解析为表,因为视图isn't referenced in a from clause。因此它超出了范围。

将与子句视为定义即时视图。因此,即使表别名与命名子查询匹配,您也没有访问查询本身中的CTE。因此,查询永远不会引用CTE的内容。

例如,下面的查询使用与表别名同名的what子句,但主要查询doesn't select from the CTE。所以就像架构中的任何其他视图一样,数据库会忽略其内容,并且查询不会读取dual:

set serveroutput off

with t1 as (
  select dummy from dual
)
  select * from t t1;
  
C1   
    1 
    2 
    3 
    4 
    5 
  
select * 
from   dbms_xplan.display_cursor( format => 'BASIC LAST' );

----------------------------------                              
| Id  | Operation         | Name |                              
----------------------------------                              
|   0 | SELECT STATEMENT  |      |                              
|   1 |  TABLE ACCESS FULL| T    |                              
----------------------------------
复制


如果您确实访问了CTE,则数据库将不再能够解决该查询并引发错误:
with t1 as (
  select dummy from dual
)
  select * from t t1, t1;
  
ORA-00918: column ambiguously defined
复制

文章转载自ASKTOM,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论