【问题标题】:Variable scope in SQL `order`.id unknown columnSQL `order`.id 未知列中的变量范围
【发布时间】:2010-07-13 13:14:40
【问题描述】:

在以下查询中,我在 INNER JOIN 中的 order.id 引用引发了错误 Unknown column 'order.id' in 'on clause'id 列确实存在。

任何想法为什么它不能通过子查询访问?

SELECT
    SUM(price+shipping_price) AS total_sales,
    COUNT(id) AS total_orders,
    AVG(price+shipping_price) AS order_total_average,
    (SELECT
            SUM(quantity)
        FROM `order_product`
        WHERE `order`.id = order_product.order_id
    ) as total_units,
    SUM(price+shipping_price)/7 as daily_average,
    (SELECT
            SUM(order_product.price * order_return_product.quantity)
        FROM order_return_product
        INNER JOIN order_product ON (
            order_product.order_id = `order`.id AND
            order_product.product_id = order_return_product.product_id AND
            order_product.vehicle_id = order_return_product.vehicle_id
        )
        WHERE return_id IN (
            SELECT
                id
            FROM order_return
            WHERE status_id != 3 AND
            order_return.order_id = `order`.id
        )
    ) as total_returns
FROM `order`
WHERE created >= 1278388801 AND
created <= 1279079999 AND
fraud = 0 AND
type_id = 4

当我在 INNER JOIN 中注释掉 order.id 时,我没有收到任何错误

【问题讨论】:

  • 你没有在最里面的SELECT 中包含order,所以那时它必须是未知的,不是吗?
  • 它只是在 INNER JOIN 内部中断,它在我使用过的其他任何地方都可以正常工作。

标签: sql mysql mysql-error-1054


【解决方案1】:

order.id 超出了此查询的范围 - 您只处理子查询中的 order_return_productorder_product 表。

【讨论】:

  • 但是我应该仍然可以访问我认为的主查询....如果它超出范围,我怎么可以在其他子查询中使用它呢?
  • 您在另一个子查询的 WHERE 子句中使用它,这很好。该错误是因为您尝试在 ON 子句中使用 order.id 进行不使用 order 作为其表之一的查询。
【解决方案2】:

试试这个:

SELECT
    SUM(order_product.price * order_return_product.quantity)
FROM order_return_product
INNER JOIN order_product ON (
    order_product.product_id = order_return_product.product_id AND
    order_product.vehicle_id = order_return_product.vehicle_id
)
WHERE return_id IN (
    SELECT
        id
    FROM order_return
    WHERE status_id != 3 AND
    order_return.order_id = `order`.id
) 
AND order_product.order_id = `order`.id 

... 对于 total_returns 子查询

【讨论】:

    【解决方案3】:

    我认为问题是因为 order 是 mysql 的关键字所以使用

    `order`.`id `
    

       o.id
       |
       |
       |
      FROM `order` o
    

    【讨论】:

    • 我不认为是这样 - 只要它在引号中就可以工作。不过还是不错的。
    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 2016-04-30
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多