【问题标题】:Unknown Column name in field list- MySQL字段列表中的未知列名 - MySQL
【发布时间】:2016-02-03 19:02:13
【问题描述】:

在我看来,这确实是一个简单的修复,但我无法弄清楚。这是我正在研究的问题:

  1. 创建一个名为 order_item_products 的视图,该视图返回 Orders、Order_Items 和 Products 表中的列。 此视图应从 Orders 表返回以下列:order_id、order_date、tax_amount 和 ship_date。 此视图应从 Order_Items 表返回以下列:item_price、discount_amount、final_price(从商品价格中减去的折扣金额)、数量和 item_total(计算出的商品总额)。 此视图应返回 Products 表中的 product_name 列

这是我的代码:

    CREATE VIEW order_item_products AS
     SELECT o.order_id, o.order_date, o.tax_amount, o.ship_date,
                 oi.item_price, oi.discount_amount,  oi.quantity, 
             (oi.item_price - oi.discount_amount) AS actual_price,
    (actual_price * oi.quantity) AS final_price,
              p.product_name
FROM orders o 
    JOIN order_items oi on o.order_id = oi.order_id
    JOIN products p ON p.product_id = oi.product_ID;

我在字段列表中收到错误消息“未知列”“实际价格”。我究竟做错了什么?它不会计算最终价格。我删除了最终的价格语句并执行了我的查询,因此它允许它成为一列。

感谢任何帮助。

【问题讨论】:

  • 您不能在定义别名的同时使用别名。所以(actual_price * oi_quantity) 必须是((oi.item_price - oi.discount_amount) * oi.quantity)
  • 谢谢!我知道这很简单。

标签: mysql views mysql-error-1054


【解决方案1】:

您正在尝试在别名实际存在之前使用它。我认为这应该可行:

CREATE VIEW order_item_products AS
    SELECT
        o.order_id,
        o.order_date,
        o.tax_amount,
        o.ship_date,
        oi.item_price,
        oi.discount_amount,
        oi.quantity, 
        (oi.item_price - oi.discount_amount) AS actual_price,
        ((oi.item_price - oi.discount_amount) * oi.quantity) AS final_price,
        p.product_name
    FROM orders AS o 
    JOIN order_items AS oi
        ON o.order_id = oi.order_id
    JOIN products AS p
        ON p.product_id = oi.product_ID
;

【讨论】:

    【解决方案2】:

    我的版本似乎有效:

    CREATE or REPLACE view order_item_product
    AS SELECT o.order_id,o.order_date,o.tax_amount,o.ship_date,
    oi.item_price,oi.discount_amount,oi.item_price-oi.discount_amount AS final_price,oi.quantity,COUNT(oi.item_id) AS item_total,
    p.product_name
    FROM orders o,orderitems oi,product p
    WHERE o.order_id=oi.order_id
    AND p. product_id=oi. product_id;
    

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多