F
F
fuck__all__humans2017-02-01 15:11:54
SQL
fuck__all__humans, 2017-02-01 15:11:54

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);

But this is only for two categories, and for a selection of 3 categories, you will have to add 1 more JOIN and so on. There is another option
SELECT cat_id restaurant_id FROM restaurants_category WHERE cat_id = 1 AND cat_id = 2

And then iterate and sort everything using PHP. In general, I really hope for your help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2017-02-01
@fuck__all__humans

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

R
Roman Fov, 2017-02-01
@Roman-Fov

Selects those that have more than one category.
This is??? Or did I misunderstand the question?

SELECT COUNT(*) AS `count`, `restaurant_id` FROM `restaurants_category` as `r` GROUP BY `restaurant_id` HAVING COUNT(*) > 1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question