SQL Select rows using LEFT JOIN - where count is 0 matches

I need to get rows from one SQL table when there are zero matches for a specific condition in the second table. I am using SQL SELECT with LEFT JOIN. How can I create a condition with GROUP BY and COUNT to get related rows with 0 matches for a specific value ?
14 May 2021 at 05:50 PM
0pnshow more
StorStor
Hi,

To get only rows from one table with zero matches for a specific condition in the second table, you can use a subquery with SELECT and COUNT(), without using of LEFT JOIN.

For example, the following solution will get categories with zero related items:

SELECT c.category_name FROM item_categories AS c WHERE 'zero_matches' = (SELECT IF(COUNT(*) = 0, 'zero_matches', 'matches_found') FROM items AS i WHERE c.id_category = i.id_category) ORDER BY c.category_name;
You can also add GROUP BY into SQL if needed.
20 May 2021 at 10:58 AM
0pnshow more
TimTim
Share on FacebookShare on TwitterShare on LinkedInSend email
Follow us on Facebook & Twitter
2022 AnswerTabsTermsContact us