代码之家  ›  专栏  ›  技术社区  ›  ChrisB

在联接表中搜索

  •  1
  • ChrisB  · 技术社区  · 14 年前

    我有四张桌子:

    cuisines(id, name);
    
    recipes(id, cuisine_id, name, picture);
    
    ingredients(id, name);
    
    ingredients_recipes(ingredient_id, recipe_id);
    

    我在SQLite中使用这个,但我想在所有SQL语言中都是一样的?

    5 回复  |  直到 14 年前
        1
  •  0
  •   tdammers    14 年前

    根据外键将它们全部连接起来,按您感兴趣的菜系表的所有列进行筛选。

    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
  •  3
  •   Daniel Vassallo    14 年前

    你可以试试 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';
    
        3
  •  0
  •   markusk Kiril Kirilov    14 年前

    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'
    )
    
        4
  •  0
  •   Brian Hooper    14 年前

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

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

    无论如何,我认为你必须小心这个词的搭配;与其他记者相比更是如此,因为你不想错过“四个小番茄”或“一个大番茄”或“番茄泥”等配料。

        5
  •  0
  •   user359040 user359040    14 年前

    存在变体:

    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
    )