Answer the question
In order to leave comments, you need to log in
How to sort the result by the number of "caught" id?
I don’t know how else to correctly name the question)
There is a recipe_ingredients table :
+----+-----------+---------------+
| id | recipe_id | ingredient_id |
+----+-----------+---------------+
| 1 | 100 | 500 |
+----+-----------+---------------+
| 2 | 100 | 501 |
+----+-----------+---------------+
| 3 | 200 | 501 |
+----+-----------+---------------+
| 4 | 200 | 900 |
+----+-----------+---------------+
| 5 | 200 | 901 |
+----+-----------+---------------+
SELECT
recipe_id,
catch_ingredients
FROM
recipe_ingredients
WHERE
ingredient_id IN (501, 900)
GROUP BY
recipe_id
ORDER BY
catch_ingredients DESC
+-----------+-------------------+
| recipe_id | catch_ingredients |
+-----------+-------------------+
| 200 | 2 | <--- Поймали 501 и 900
+-----------+-------------------+
| 100 | 1 | <--- Поймали только 501
+-----------+-------------------+
Answer the question
In order to leave comments, you need to log in
SELECT value, COUNT(*)
FROM table
GROUP BY 1
ORDER BY 2 DESC
So what is the question?
"Find recipes that include at least one ingredient from the list?
SELECT `recipe_id`, `ingredient_id`
FROM `recipe_ingredients`
WHERE `ingredient_id` IN (501, 900)
SELECT `recipe_id`, COUNT(*) AS `count`,
SUM(`ingredient_id` IN (501, 900)) AS `avail`
FROM `recipe_ingredients`
GROUP BY `recipe_id`
HAVING `count` = `avail`
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question