昨天我遇到了一个客户端的查询,它类似于:
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中这不会飞。每当我使用派生表时,它都会抛出一个错误,所以遇到这样的场景会引起我的兴趣。我无法在interwebs上找到任何解释它的东西,希望有人可以解释派生表的别名是可选的以及何时不是。
答案 0 :(得分:2)
当您引用未唯一定义的列时,您只需要别名。这意味着该列存在于多个表/派生表中。引用可以在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;
答案 1 :(得分:1)
在这种情况下,您正在从子查询中选择所有列,因此子查询没有别名。
如果要将此子查询与另一个表或可能是另一个子查询连接,则需要使用别名,以便可以使用定义的别名引用连接列。