I have a table named products that holds all the products e.g T-Shirt and product_variants that have the associated variants of the colors, eg. Black, Blue, Green which each has a stock column - that holds the number of stocks left.
I would like to build a query that can tell me which of the products that are totally sold out, and which are not.
The stock column should be 0 to be sold out, but if its NULL or > 0, it's in stock. NULL is used when we have unlimited quantities.
This is the following result i would like to get:
product_id|soldOut|stock
------------------
1 |Yes |0
2 |Yes |0
3 |No |NULL
4 |No |1
What i tried to do, is the following:
- Grab all products
- Make a join to product_variants
- Group by product_id to only show one result per product.
- SELECTing product_id and
IF(stock > 0 OR stock IS NULL, 'No', 'Yes') as SoldOUt
Query:
SELECT p.product_id, IF(pv.stock > 0 OR pv.stock IS NULL, 'No', 'Yes') as SoldOUt
FROM products p
JOIN product_variants pv ON (`pv`.`product_id` = `p`.`product_id`)
GROUP BY p.product_id
The results is that soldOut is not correct - it seems like it just takes a random row of the variants and check the stock of this and answers.
Instead, It should check all of the variants row and see if any of them is not yet soldOut (with the if statement above) and then return one final answer for that product.
What have I done wrong and how can this be accomplished?