[英]MYSQL find all rows where second row have given values
my database table looks like: 我的数据库表如下所示:
╔════╦═══════════╦═══════════╗
║ ID ║ RECIPE_ID ║ NAME ║
╠════╬═══════════╬═══════════╣
║ 1 ║ 1 ║ Apple ║
║ 2 ║ 2 ║ Apple ║
║ 3 ║ 2 ║ Orange ║
║ 4 ║ 3 ║ Kiwi ║
║ 5 ║ 1 ║ Kiwi ║
║ 6 ║ 3 ║ Cherry ║
║ 7 ║ 3 ║ Banana ║
╚════╩═══════════╩═══════════╝
When i'm querying mysql for "Apple"
AND "Orange"
, so i should get the RECIPE_ID
2 because "Apple"
and "Orange"
have the same RECIPE_ID
or second example: 当我向mysql查询"Apple"
和"Orange"
,我应该得到RECIPE_ID
2,因为"Apple"
和"Orange"
具有相同的RECIPE_ID
或第二个示例:
When looking for "Kiwi"
AND "Banana"
i should get the RECIPE_ID
3 当寻找"Kiwi"
和"Banana"
我应该得到RECIPE_ID
3
Here is my SQL I have tried 这是我尝试过的SQL
SELECT recipe_id, name
FROM foodtipps.rezepte_zutaten
WHERE name='Kiwi' AS 'NAME1' AND
name='Banana AS 'NAME2' GROUP BY recipe_id
Hope you understand my problem. 希望你理解我的问题。 Thank you! 谢谢!
If you have only two value for search you can use a inner join 如果只有两个搜索值,则可以使用内部联接
select a.recipe_id
from my_table as a
inner join my_table as b on a.recipe_id = b.recipe_id
where a.name ='Apple'
and b.name ='Orange';
This can be extended to many more ingredients easily: 这可以轻松扩展到更多成分:
SELECT recipe_id
FROM theTable
WHERE name IN ('Apple', 'Orange')
GROUP BY recipe_id
HAVING COUNT(*) = 2 /* number of ingredients in the list */
The answer given by scaisEdge solves the problem you asked . scaisEdge给出的答案解决了您提出的问题 。
It's possible to extend this to support an indefinite number of ingredients, but its a bit messy adding a join to the table each time, hence... 可以扩展它以支持无限数量的成分,但是每次添加一个联接到表中都会有点混乱,因此...
SELECT recipe_id, COUNT(DISTINCT name)
FROM recipe
WHERE name in (
'Apple',
'Orange',
...
)
GROUP BY recipe_id
ORDER BY 1 DESC;
You might also add a HAVING COUNT(DISTINCT name)=xxx
where xxx is your number of ingredients before the ORDER BY. 您还可以添加一个HAVING COUNT(DISTINCT name)=xxx
,其中xxx是ORDER BY之前您的配料数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.