Answer the question
In order to leave comments, you need to log in
How to write an SQl query?
Guys, help, I've been digging for more than 3 hours in Yandex and Google, and I haven't found anything.
I have a table of this format restaurants_category:
id | cat_id | restaurant_id
1 | 1 | 1
2 | 1 | 2
3 | 1 | 3
4 | 2 | 2
5 | 3 | 1
6 | 4 | 2
7 | 4 | 3
I need to write a SQL query that would select a restaurant_id that belonged to more than one cat_id.
For example, I want to select a restaurant_id that belongs to both cat_id = 1 and cat_id = 2, then restaurant_id will be 2. If I need to select a restaurant_id that belongs to both cat_id = 1 and cat_id = 2 and cat_id = 4, then the restaurant_id will also be equal to 2.
I have a variant of the sql query:
SELECT
"A".restaurant_id
FROM
restaurants_category AS "A"
INNER JOIN
restaurants_category AS "B"
ON
("A".restaurant_id = "B".restaurant_id AND
"A".cat_id = 1 AND
"B".cat_id = 2);
SELECT cat_id restaurant_id FROM restaurants_category WHERE cat_id = 1 AND cat_id = 2
Answer the question
In order to leave comments, you need to log in
Remove the `id` field from the table and make the pair (`cat_id`, `restaurant_id`) the primary key, because there should not be duplicates of such pairs. Then the query can be simplified
SELECT `restaurant_id`
FROM `restaurants_category`
WHERE `cat_id` IN (1, 2)
GROUP BY `restaurant_id`
HAVING COUNT(*) = 2
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question