Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return null rows if not found in where mysql

Imagine have a request Like :

Select product_id,category, price  FROM mytable
WHERE category IN('fish', 'chips', 'nuggets')

But no products_id has a ‘chips’ category. Then it will return something like:

Product_id category price
001 fish 1,3
001 nuggets 1,4
002 fish 4,1
002 nuggets 3,1
003 fish 1,41
003 nuggets 44,1

But I want display null for each conditions not found in where conditions:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Product_id category price
001 fish 1,3
001 nuggets 1,4
001 chips NULL
002 fish 4,1
002 nuggets 3,1
002 chips NULL
003 fish 1,41
003 nuggets 44,1
003 chips NULL

How can I do that??

>Solution :

Use a calendar table approach along with a cross join:

SELECT p.product_id, c.category, t.price
FROM (SELECT DISTINCT category FROM mytable) c
CROSS JOIN (SELECT DISTINCT product_id FROM mytable) p
LEFT JOIN mytable t
    ON t.category = c.category AND
       t.product_id = p.product_id
WHERE c.category IN ('fish', 'chips', 'nuggets')
ORDER BY p.product_id, c.category;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading