Oracle sql派生表-可选别名

Oracle sql派生表-可选别名,oracle,derived-table,Oracle,Derived Table,我昨天遇到一个客户的问题,它是这样的: select count(*) as countall, person, location from (select custid, min("Date") as theDate, person, data.location from data join customer o

我昨天遇到一个客户的问题,它是这样的:

select count(*) as countall,
          person,
          location 
  from (select custid,
               min("Date") as theDate,
               person,
               data.location  
        from data join 
             customer on customer.customerid = custid 
        where status = 1 
          and custid <> -1 
       group by custid,
                person,
                data.location)  --[NO ALIAS]
   group by person,location

我在Oracle的时间不多,但据我所知,在MS SQL中,这是不可能实现的。每当我使用派生表时,它都会抛出一个错误,因此遇到这样的情况会激发我的兴趣。我在InterWeb上找不到任何解释,希望有人能解释派生表的别名是可选的,而派生表的别名不是可选的。

在本例中,您选择的是子查询中的所有列,因此子查询没有别名


如果要将此子查询与另一个表或另一个子查询联接,则需要使用别名,以便可以使用定义的别名引用联接列。

引用未唯一定义的列时,只需使用别名。这意味着该列存在于多个表/派生表中。引用可以在select语句中,也可以在join语句中。如果所有列都是唯一的,则不需要别名

为了清晰起见,我更喜欢一直使用别名,因为它有助于PL/SQL中的Intellisense

--ALIAS needed, because the 'a' column referenced is not unique
--this will throw an error
select a, a, b, c
  from (select 'A1' as a, 'B1' as b, 'C1' as c from dual),
       (select 'A2' as a from dual);
--this will not throw an error
select t1.a, t2.a, b,c
  from (select 'A1' as a, 'B1' as b, 'C1' as c from dual) t1,
       (select 'A2' as a from dual) t2;
;

--ALIAS not needed for join, because all referenced columns are unique
select a, b, c, d, e, f
  from (select 'A' as a, 'B' as b, 'C' as c from dual)
  join (select 'D' as d, 'E' as e, 'F' as f from dual)
    on a = d;

--ALIAS needed for join, because the 'x' column referenced is not unique
--this will throw an error
select a
  from (select 'A' as a, 'B' as b, 'C' as c, 'X' as x from dual)
  join (select 'D' as d, 'E' as e, 'F' as f, 'X' as x from dual)
    on x = x;
--this will not throw an error
select a
  from (select 'A' as a, 'B' as b, 'C' as c, 'X' as x from dual) t1
  join (select 'D' as d, 'E' as e, 'F' as f, 'X' as x from dual) t2
    on t1.x = t2.x;

不需要使用别名。然而,如果你需要参考它,它是需要的。这会起作用的。别名是可选的,但建议使用。在您发布的代码中,这并不是必需的,但建议在内联视图之外有表,以便可以使用联接,并且在列名常见或不明确的情况下,这是必需的。这因平台而异。在Oracle subselects中,派生表不需要您所称的别名,事实上它称为关联名。我要说的是,始终将它们作为最佳实践来使用。+对于关联名称,我试图理解特定于平台的术语