簡體   English   中英

MYSQL查找第二行具有給定值的所有行

[英]MYSQL find all rows where second row have given values

我的數據庫表如下所示:

╔════╦═══════════╦═══════════╗
║ 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    ║
╚════╩═══════════╩═══════════╝

當我向mysql查詢"Apple""Orange" ,我應該得到RECIPE_ID 2,因為"Apple""Orange"具有相同的RECIPE_ID或第二個示例:

當尋找"Kiwi""Banana"我應該得到RECIPE_ID 3

這是我嘗試過的SQL

SELECT recipe_id, name 
FROM foodtipps.rezepte_zutaten 
WHERE name='Kiwi' AS 'NAME1' AND 
name='Banana AS 'NAME2' GROUP BY recipe_id

希望你理解我的問題。 謝謝!

如果只有兩個搜索值,則可以使用內部聯接

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

這可以輕松擴展到更多成分:

SELECT recipe_id
FROM theTable
WHERE name IN ('Apple', 'Orange')
GROUP BY recipe_id
HAVING COUNT(*) = 2 /* number of ingredients in the list */

scaisEdge給出的答案解決了您提出的問題

可以擴展它以支持無限數量的成分,但是每次添加一個聯接到表中都會有點混亂,因此...

 SELECT recipe_id, COUNT(DISTINCT name)
 FROM recipe
 WHERE name in (
     'Apple',
     'Orange',
      ...
 )
 GROUP BY recipe_id
 ORDER BY 1 DESC;

您還可以添加一個HAVING COUNT(DISTINCT name)=xxx ,其中xxx是ORDER BY之前您的配料數量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM