SELECT `products`.*, SUM(orders.total_count) AS revenue, SUM(orders.quantity) AS qty FROM `products`
LEFT JOIN `orders` ON (`products`.`id` = `orders`.`product_id`)
WHERE (`orders`.`status` = 'delivered' OR `orders`.`status` = 'new')
GROUP BY `products`.`ID` ORDER BY products.ID DESC LIMIT 10 OFFSET 0
This is what I got. Currently it only grab the products which have any orders that are either delivered or new.
That WHERE statement is only for the correct calculation of SUM(orders.total_count) and SUM(orders.quantity) –
I would like to grab all the products, and if there is any orders for this product then it should look at that where statement to make sure that the order we grab are new or delivered.
The short answer is change
WHEREtoAND.Really, what that means is, the predicate on the “
orders.status” column needs to be in theONclause, rather than theWHEREclause.In your query, that predicate is doing the equivalent of an “
orders.status IS NOT NULL“, which is going to “throw out” any of the NULL rows that were created by the LEFT JOIN.The easiest way to think of the LEFT (OUTER) JOIN is that it’s creating a dummy “orders” row to match to a “products” row, when there is no other “orders” row that matches. And that dummy row consists of all NULL values.