如何进行查询显示?

时间:2013-11-15 18:06:28

标签: mysql sql

我有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

但它不能正常工作。最后,我想得到这个结果。

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

请帮助

P.S:抱歉我的英文不好

2 个答案:

答案 0 :(得分: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子句中的成分数。

答案 1 :(得分: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|
+----------+---------------+