简体   繁体   中英

SQL query with SUM + computing, using LEFT JOINs

I have problem with SQL query. If given order contains items, witch does not contains sub-items, then is total price of order zero, otherwise this query works fine.

SELECT o.`id`, o.`date`, c.`name`,
      ((i.`quantity` * i.`price`) +
      SUM(i.`quantity` * subi.`quantity_kg` * subi .`price`)) as total_price
FROM `order` o
JOIN `customer` c ON o.`id_customer`=c.`id`
LEFT JOIN `order_item` i ON i.`id_order`= o.`id`
LEFT JOIN `order_subitem` subi ON si.`id_product`= i.`id_product`
GROUP BY o.`id`

Thank you for help.

Use coalesce of ifnull on your subitem fields:

SELECT o.`id`, o.`date`, c.`name`,
      ((i.`quantity` * i.`price`) +
      SUM(i.`quantity` * coalesce(subi.`quantity_kg`, 0) * coalesce(subi .`price`, 0))) as total_price

This makes sure, that these fields won't end up being null ruining your whole calculation. Eg null+1 = null

SELECT o.`id`, o.`date`, c.`name`,
      ((i.`quantity` * i.`price`) +
      SUM(i.`quantity` * IFNULL(subi.`quantity_kg`, 0) * IFNULL(subi .`price`, 0))) as total_price
FROM `order` o
JOIN `customer` c ON o.`id_customer`=c.`id`
LEFT JOIN `order_item` i ON i.`id_order`= o.`id`
LEFT JOIN `order_subitem` subi ON si.`id_product`= i.`id_product`
GROUP BY o.`id`

if you know order_item should exist, then you should use an INNER JOIN for this table.

I suspect the problem is that you are getting NULL returned, rather 0. To fix this, you simply need the coalesce function to handle the NULL cases:

SELECT o.`id`, o.`date`, c.`name`,
       ((i.`quantity` * i.`price`) +
        SUM(i.`quantity` * coalesce(subi.`quantity_kg`, 0) * coalesce(subi .`price`, 0))
       ) as total_price
FROM `order` o JOIN
     `customer` c
     ON o.`id_customer`=c.`id` LEFT JOIN
     `order_item` i
     ON i.`id_order`= o.`id` LEFT JOIN
     `order_subitem` subi ON si.`id_product`= i.`id_product`
GROUP BY o.`id` 

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