使用子查询中的别名

时间:2017-08-24 10:48:13

标签: sql oracle

我想使用子查询中的别名。

Fruit table:
name:    is_bio:    from_id:   to_id:
Apple    yes        Spain      Italy

Country table:
id:      packaging_type:    packaging_quantity:
Italy    wood box           12
Spain    paper box          18

我尝试过这样的事情:

with subquery as (SELECT a.packaging_type, a.packaging_quantity, b.packaging_type, b.packaging_quantity 
FROM fruit
    inner join country a on a.country.id = fruit.from_id
    inner join country b on b.country.id = fruit.to_id
WHERE fruit.name = 'Apple')
SELECT a.packaging_quantity from subquery;

但我收到了一个错误:

ORA-00904: "A"."PACKAGING_QUANTITY": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 7 Column: 14

1 个答案:

答案 0 :(得分:3)

这是对问题的原始版本的回答。

您的CTE有四列,但只有两列专栏,packaging_typepackaging_quantity。表别名不是完全限定列名(即包括别名或表名),而只是列名本身。

您需要使用as为其指定不同的名称,例如:

with subquery as (
      select a.packaging_type as packaging_type_a,
             a.packaging_quantity as packaging_quantity_a, 
             b.packaging_type as packaging_type_b,
             b.packaging_quantity as packaging_quantity_b
      from fruit inner join
           country a
           on a.country.id = fruit.from_id inner join
           country b
           on b.country.id = fruit.to_id
      where fruit.name = 'Apple'
     )
select packaging_quantity_a
from subquery;