2013-11-15 106 views
0

我有3個表如何使查詢顯示?

recipe 
+----------+---------+ 
| recipe_id|  name| 
+----------+---------+ 
|   1| name_1| 
+----------+---------+ 
|   2| name_2| 
+----------+---------+ 
|   3| name_3| 
+----------+---------+ 

ingredient 
+--------------+---------+ 
| ingredient_id|  name| 
+--------------+---------+ 
|    7| cheese| 
+--------------+---------+ 
|    9| pepper| 
+--------------+---------+ 
|   16| tomato| 
+--------------+---------+ 

recipe_ingredient 
+----------+---------------+ 
| recipe_id| ingredient_id| 
+----------+---------------+ 
|   1|    7| 
+----------+---------------+ 
|   1|    16| 
+----------+---------------+ 
|   2|    7| 
+----------+---------------+ 
|   3|    7| 
+----------+---------------+ 
|   3|    9| 
+----------+---------------+ 
|   3|    16| 
+----------+---------------+ 

如何來僅顯示那些在其中的成分是嚴格相同的食譜? 我用它

SELECT r.name, r.recipe_id 
    FROM recipe AS r 
    LEFT JOIN recipe_ingredient AS r_i ON r_i.ingredient_id = '7' 
       OR r_i.ingredient_id = '16' 
WHERE r.recipe_id=r_i.recipe_id 

但它並不因爲我需要to.In工作進行到底,我要得到這樣的結果。

+----------+---------------+ 
|  name|  recipe_id| 
+----------+---------------+ 
| name_1|    1| 
+----------+---------------+ 
| name_3|    3| 
+----------+---------------+ 

幫助,請

P.S:對不起我的英文不好

+0

配方號1不具有相同的成分。 – Sebas

+0

他的意思與他檢查的成分列表相同,在本例中爲7和16。 – Barmar

+0

請添加您用當前代碼獲得的輸出。 – sushain97

回答

0
SELECT `r`.`recipe_id`, `r`.`name` 
    FROM `recipe` `r` 
    JOIN (SELECT `r_i`.`recipe_id` 
      FROM `recipe_ingredient` `r_i` 
      WHERE `r_i`.`ingredient_id` IN (7,16) 
      GROUP BY `r_i`.`recipe_id` 
      HAVING COUNT(`recipe_id`) >= 2 
    ) `result` ON `r`.`recipe_id` = `result`.`recipe_id` 

例如:

$ingred_arr = array(7,16); 
$count_ingred = count($ingred_arr); 

$query = " 
    SELECT `r`.`recipe_id`, `r`.`name` 
    FROM `recipe` `r` 
    JOIN (SELECT `r_i`.`recipe_id` 
      FROM `recipe_ingredient` `r_i` 
      WHERE `r_i`.`ingredient_id` IN (".implode(',',$ingred_arr).") 
      GROUP BY `r_i`.`recipe_id` 
      HAVING COUNT(`recipe_id`) >= ".$count_ingred." 
    ) `result` ON `r`.`recipe_id` = `result`.`recipe_id` " 

結果:

+----------+---------------+ 
|  name|  recipe_id| 
+----------+---------------+ 
| name_1|    1| 
+----------+---------------+ 
| name_3|    3| 
+----------+---------------+ 
0
SELECT r.name, r.recipe_id 
FROM recipe AS r 
JOIN (SELECT recipe_id, 
      COUNT(*) c AS total_ingredients, 
      SUM(ingredient_id IN (7, 16)) AS matching_ingredients 
     FROM recipe_ingredient 
     GROUP BY recipe_id 
     HAVING total_ingredients = 2 AND matching_ingredients = 2) AS r_i 
ON r.recipe_id = r_i.recipe_id 

一般來說,HAVING子句中的值應該是IN子句中成分的數量。

+0

這並不是我所需要的,因爲我不知道配方中每種成分的含量。 我可以在表中添加另一列嗎? 'HAVING total_ingredients = r.count_ingredients AND matching_ingredients = 2' 如果我有25,000個食譜,它是否會工作得很快? –

+0

您可以將'quantity'列添加到'recipe_ingredient'表中。我的查詢不關心。 – Barmar

+0

但是,如果你只想找到需要4個西紅柿和3片奶酪的食譜,它會變得更加複雜。 – Barmar