Search code examples
mysqlleft-joincategoriesrelational-division

MySQL select item from several categories returns no results


I have this SQL-query:

SELECT DISTINCT c.id, c.name 
FROM cars c LEFT JOIN 
     _rel_cars_categories rcc ON c.id=rcc.car_id 
WHERE (rcc.category_id=33 AND rcc.category_id=51) 
  AND c.status >=10

The tables:

Unfortunally, it returns 0 results. When I replace AND whith OR, it works fine, but I want to get all that ar in both of these categories. It also can be 3, 4, 5... categories. How can I get the right result?


Solution

  • To select cars which have both 33 and 51 as category_id, try this:

    SELECT c.id, c.name 
    FROM cars c JOIN 
         _rel_cars_categories rcc ON c.id=rcc.car_id 
    WHERE rcc.category_id IN (33,51) AND c.status >=10
    GROUP BY c.name
    HAVING count( distinct rcc.category_id ) = 2