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 ?
0
give a positive ratinggive a negative rating
14 May 2021 at 05:50 PM
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.
0
give a positive ratinggive a negative rating
20 May 2021 at 10:58 AM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us