oracle:你能为from子句分配一个别名吗?

时间:2011-02-09 01:40:06

标签: sql oracle table-alias

可以为from子句分配别名吗?像:

select a - b "Markup" from retail a, cost b;
编辑:抱歉,我输入的速度有点太快,并试图将问题简化到没有任何意义的地方

我真正想要做的是使用别名来比较同一个表中两个发布日期之间的月份。这是我发现的作品:

select distinct to_char(months_between((select distinct pubdate
                                        from books3 
                                        where pubid = 2), 
                                       (select distinct pubdate 
                                        from books3 
                                        where pubid = 4)), '99.99') "Answer"
                              from books3

我希望它看起来像这样:

select distinct months_between(a,b)
from (select distinct pubdate 
       from books3 
       where pubid = 2 as a), 
     (select distinct pubdate 
      from books3 
      where pubid = 4 as b)

但这不起作用

2 个答案:

答案 0 :(得分:15)

是的,Oracle支持表别名。它支持AS列表中的SELECT,但不支持FROM列表中的SELECT a.col - b.col AS markup FROM RETAIL a, COST b WHERE b.id = a.id

AS

大多数数据库都支持省略WHERE关键字。

也就是说,表别名不是列别名 - 您仍然需要引用SELECT子句中相应表中的特定列,就像您在我的示例更新中看到的那样。我还添加了SELECT x.col FROM (SELECT t.col, MAX(t.date) FROM TABLE t GROUP BY t.col) x 条件,因此查询不会返回笛卡尔积。

派生表/内联视图有时需要表别名(AKA子查询,但我发现术语非常模糊):

SELECT DISTINCT TO_CHAR(MONTHS_BETWEEN(x.pubdate, y.pubdate), '99.99') AS "Answer"
 FROM (SELECT DISTINCT a.pubdate FROM BOOKS3 a WHERE a.pubid = 2) x,
      (SELECT DISTINCT b.pubdate FROM BOOKS3 b WHERE b.pubid = 4) y

这是您的查询:

你的问题是你把表别名放在派生表中,当它需要在括号/括号之外时:

{{1}}

您需要独特的原因是因为笛卡尔积。

答案 1 :(得分:0)

最接近你的方法是将AS alias移出子查询

select distinct months_between(a.pubdate,b.pubdate)
from (select distinct pubdate 
       from books3 
       where pubid = 2) as a ,
     (select distinct pubdate 
      from books3 
      where pubid = 4) as b;

但是,查询仍然没有多大意义。如果pubid=2有2条记录,pubid=4有3条记录,则输出中会有6行....

months_between(a1, b1)
months_between(a2, b1)
months_between(a1, b2)
months_between(a2, b2)
months_between(a1, b3)
months_between(a2, b3)

我怀疑你实际上正在进行一些分组,所以这将比较每个bookid级别的pubid = 2和pubid = 4个条目。

select
    bookid,
    to_char(months_between(
        max(case when pubid=2 then pubdate end),
        max(case when pubid=4 then pubdate end)), '99.99') "Answer"
from books
group by bookid;