简体   繁体   中英

Using parent field in subquery

I've got the following query on a Prestashop 1.4 DB and I can't figure out how to use parent id_order field in the subquery.

Error message is "#1054 - 'o.id_order' field unknown in where clause" .

I tried using a left join but getting same error.

Both tables order and order_detail have an id_order field. There can be many order_detail rows for one order.

SELECT 
    o.invoice_date,
    o.invoice_number,
    (   
    SELECT ROUND(SUM(price),2) FROM
        (
            SELECT (od.product_price * od.tax_rate / 100) as `price`
                FROM order_detail od 
                WHERE od.id_order = o.id_order
        ) as `tmp`
    ) as `tax`
FROM `order` o
WHERE o.invoice_number != 0 ...

Is it because I try to use it in a where clause?

On the following query (can't use it on this case), o.id_order is well known...

(   
    SELECT ROUND(SUM(total_amount),2)
    FROM order_detail_tax ot 
    WHERE ot.id_tax = 2 AND ot.id_order_detail 
    IN (
        SELECT od.id_order_detail 
            FROM order_detail od 
            WHERE od.id_order = o.id_order
    )
) as `Tax`,

Try using only one subquery:

SELECT 
  o.invoice_date,
  o.invoice_number,
  (   
    SELECT ROUND(SUM(od.product_price * od.tax_rate / 100), 2)
      FROM order_detail od 
     WHERE od.id_order = o.id_order
  ) as `tax`
FROM `order` o
WHERE o.invoice_number != 0

Because, if you nest two subquerys the most inner one will not be able to reference to the outer one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM