【问题标题】:i want someone to check my code and Identified the syntax error我希望有人检查我的代码并确定语法错误
【发布时间】:2019-10-12 13:41:23
【问题描述】:

问题是:

对于至少在 PC、笔记本电脑或打印机表之一中拥有模型的每个制造商,确定其产品的最高价格。

输出:制造商;如果给定制造商的产品价格中有NULL值,则显示该制造商的NULL值,否则显示最高价格。

数据库是: 简短的数据库描述“计算机公司”

数据库方案由四个表组成:

Product(maker, model, type)
PC(code, model, speed, ram, hd, cd, price)  
Laptop(code, model, speed, ram, hd, screen, price)  
Printer(code, model, color, type, price)  

产品表包含有关制造商、型号和产品类型(“PC”、“笔记本电脑”或“打印机”)的数据。假定产品表中的型号对于所有制造商和产品类型都是唯一的。 PC 表中的每台个人计算机均由唯一代码明确标识,并通过其型号(外键指产品表)、处理器速度(以 MHz 为单位)-速度字段、RAM 容量(以 Mb 为单位)-ram 进行额外表征, 硬盘驱动器容量 (Gb) – hd, CD-ROM 速度 (例如, '4x') - cd, 以及它的价格。 Laptop 表与 PC 表类似,不同之处在于它包含的不是 CD-ROM 速度,而是屏幕尺寸(以英寸为单位)——屏幕。对于打印机表中的每个打印机型号,其输出类型('y' 表示彩色,'n' 表示单色)- 颜色字段、打印技术('Laser'、'Jet' 或 'Matrix')- 类型和价格已指定。

代码:

select maker,max( price ) 
from 
    ( 
        select maker, max( l.price) 
        from product p left join laptop l on p.model = l.model 
        group by maker 
        union all select maker, max( pr.price) 
        from product p left join printer pr on p.model = pr.model 
        group by maker 
        union all select maker, max( pc.price) 
        from product p left join pc on p.model = pc.model 
        group by maker 
    ) as h 
group by maker ;

它给了我这个错误:

查询错误。代码:(933) ORA-00933: SQL command not properly ended.

我不知道问题出在哪里。

【问题讨论】:

    标签: sql database oracle subquery union


    【解决方案1】:

    您的查询如下所示:

    SELECT ...
    FROM (
        SELECT ... FROM ...
    ) AS h
    

    问题是Oracle不允许AS关键字给派生表起别名。您需要删除该关键字。

    Example on DB Fiddle:

    SELECT * FROM (
        SELECT 1 FROM DUAL
    ) as X
    
    ORA-00933: SQL command not properly ended
    

    您的查询的另一个问题是您在 UNIONed 子查询中使用聚合,但您没有为使用聚合函数的列设置别名:

    select 
        maker,
        max( l.price) -- no column alias
    from product p ...
    

    然后在你做的子查询中:

    select maker,max( h.price ) 
    

    这将引发错误ORA-00904: "PRICE": invalid identifier,因为外部查询中不存在price。您需要为内部查询中的列设置别名。

    select 
        maker,
        max( l.price) price
    from product p ...
    

    您的查询的最终版本:

    select maker,max( price ) 
    from 
        ( 
            select maker, max( l.price) price 
            from product p left join laptop l on p.model = l.model 
            group by maker 
            union all select maker, max( pr.price) 
            from product p left join printer pr on p.model = pr.model 
            group by maker 
            union all select maker, max( pc.price) 
            from product p left join pc on p.model = pc.model 
            group by maker 
        ) h 
    group by maker ;
    

    【讨论】:

    • 查询错误。代码:(904)ORA-00904:“价格”:无效标识符
    • 这是我删除别名时给我的结果
    • @afbigdad:是的,这是您代码的另一个问题。我的回答中也有解释。
    • 您的查询在主数据库上产生了正确的结果集,但它在第二个测试失败,检查数据库 * 错误的记录数(超过 6 个)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2011-07-06
    • 2019-07-25
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多