logiacer logiacer - 2 months ago 8
SQL Question

Getting categories from table if there's any service binded to the category id in another table

SELECT * FROM categories WHERE status = 1


I would like to get results from categories if the "services" table has any data for that specific category id. I was thinking about Left join or something like that. Any suggestions? (I use PHP btw)

Answer

You can use EXISTS:

SELECT c.* 
FROM categories AS c
WHERE c.status = 1 AND EXISTS (SELECT 1
                               FROM services AS s
                               WHERE s.category_id = c.id)
Comments