Since you say you want the subtotal, i assume that you want only to calculate the value for each line of the orders table. To get that you have to remove the DISTINCT
and the GROUP BY
. (DISTINCT
and GROUP BY
are a little weird done together for something like this, and if you want every row to be returned with the subtotal, you don't need them):
SELECT orders.*,
IF(orders.price_type = 1,
products.price * orders.quantity,
products.discount_price * orders.quantity) AS subtotal
FROM orders
LEFT JOIN products ON orders.product_id = products.id
This will get you the subtotal for every line in the orders table.
If you want the results GROUPED BY order_id
, you can't really do SELECT *
since the GROUP BY will make wrong assumptions about the other columns and you end up with wrong results, like you experienced. you can do:
SELECT orders.order_id,
orders.order_date,
SUM(IF(orders.price_type = 1,
products.price * orders.quantity,
products.discount_price * orders.quantity)) AS subtotal
FROM orders
LEFT JOIN products ON orders.product_id = products.id
GROUP BY orders.order_id, orders.order_date