views:

36

answers:

3

In the following query, the error Unknown column 'order.id' in 'on clause' is being thrown by my order.id reference in the INNER JOIN. The id column does indeed exist.

Any ideas why it's not accessible via the sub query?

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

I get no errors when I comment out order.id within the INNER JOIN

A: 

I think problem is because order is keyword for mysql so use

`order`.`id `

OR

   o.id
   |
   |
   |
  FROM `order` o
Salil
I don't think this is it - it will work as long as it is in quotes. But good catch nevertheless.
Pekka
+1  A: 

The order.id is out of scope in this query - you're only dealing with the order_return_product and order_product tables in the subquery.

Mat
But I should still have access to the main query I thought.... and if it's out of scope, how come I can utilize it in the other sub query just fine?
Webnet
You are using it in a WHERE clause in the other subquery, so that's fine. The error is because you are trying to use `order`.`id` in an ON clause for a query that does not use `order` as one of its tables.
Mat
A: 

try this:

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 

... for the total_returns subquery

ceteras
Perfect! Though I'm still wondering why that was out of scope...
Webnet
+1 for this question, I'd like to find out why too.
ceteras