Oracle sql derived table - 可选别名

Oracle sql derived table - optional aliasing

昨天遇到一个客户的查询,大概是这样的:

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 据我所知,这行不通。任何时候我使用派生的 table 它都会抛出错误,所以遇到这样的场景激起了我的兴趣。我在互联网上找不到任何解释,希望有人可以解释派生 tables 的别名是可选的以及何时不是的场景。

在这种情况下,您要从子查询中选择所有列,因此编写的子查询没有别名。

如果您要将此子查询与另一个 table 或另一个子查询连接起来,您可能需要别名,以便您可以使用定义的别名引用连接列。

您只需要在引用非唯一定义的列时使用别名。这意味着该列存在多个 table/derived table。引用可以在 select 语句或连接中。如果所有列都是唯一的,则不需要别名。

为了清楚起见,我更喜欢一直使用别名,因为它有助于 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;