Вопрос

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?

Это было полезно?

Решение

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

Другие советы

Your problem is here: WHERE (rcc.category_id=33 AND rcc.category_id=51).

Obviously a category can only be 33 OR 51. What you're looking for is likely to be WHERE ID IN (33,51) which will then return a match for any of the provided values.

So your final query should look like:

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 IN (33,51) AND c.status >=10
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top