在连接表中搜索

时间:2010-07-30 11:02:27

标签: sql sqlite mysql

我有四张桌子:

cuisines(id, name);

recipes(id, cuisine_id, name, picture);

ingredients(id, name);

ingredients_recipes(ingredient_id, recipe_id);

最后一个表格引用了食谱和配料之间的多对多关系。我如何选择所有含有西红柿的菜肴(即菜肴的配方中含有被称为“番茄”的配料)?

我在SQLite中使用它,但我猜它在所有SQL语言中都是一样的?

5 个答案:

答案 0 :(得分:3)

您可能需要尝试INNER JOIN所有四个表,如下例所示:

SELECT      DISTINCT c.name
FROM        cuisines AS c
INNER JOIN  recipes AS r ON (r.cuisine_id = c.id)
INNER JOIN  ingredients_recipes AS ir ON (ir.recipe_id = r.id)
INNER JOIN  ingredients AS i ON (i.id = ir.ingredient_id)
WHERE       i.name = 'tomatoes';

答案 1 :(得分:0)

根据外键加入所有内容,过滤在ingredient_name ='Tomatoe'上,按照您感兴趣的菜肴表的所有列进行分组。

SELECT cuisine.id, cuisine.name
  FROM cuisine
  INNER JOIN recipe on recipe.cuisine_id = cuisine.id
  INNER JOIN ingredients_recipes ir ON ir.recipe_id = recipe.id
  INNER JOIN ingredients on ingredients.id = ir.ingredient_id
  WHERE ingredients.name = 'Tomatoe'
  GROUP BY cuisine.id, cuisine.name

答案 2 :(得分:0)

子查询变体:

SELECT name
FROM cuisines
WHERE id IN (
    SELECT cuisine_id 
    FROM recipes r 
    JOIN ingredients_recipes ir ON r.id = ir.recipe_id
    JOIN ingredients i ON ir.ingredient_id = i.id
    WHERE i.name = 'Tomatoes'
)

答案 3 :(得分:0)

我建议使用子查询而不是连接。有点像...

SELECT *
    FROM cuisine
    WHERE cuisine_id IN (
             SELECT cuisine_id
                 FROM recipe
                 WHERE recipe_id IN (
                         SELECT recipe_id
                             FROM recipe_ingredients
                             WHERE ingredient_id IN (
                                        SELECT id
                                        FROM ingredients
                                        WHERE TOUPPER(name) LIKE '%TOMATO%')));

无论如何,我认为你必须小心这个词的匹配;比其他记者更多,因为你不想错过'四小番茄'或'一大番茄'或'番茄酱'等食材。

答案 4 :(得分:0)

EXISTS变种:

SELECT name
FROM cuisines c
WHERE EXISTS
(   SELECT NULL 
    FROM recipes r 
    JOIN ingredients_recipes ir ON r.id = ir.recipe_id
    JOIN ingredients i ON ir.ingredient_id = i.id and i.name = 'tomatoes'
    WHERE r.cuisine_id = c.id
)