mysql查询哪里没有Hierarchical表

时间:2011-04-24 05:20:09

标签: mysql

所以基本上我一起加入3张桌子。主表是配方,然后是成分列表然后成分。

所以我需要一个只有配方包含NO鸡肉的查询。我遇到的问题是,因为食谱在我使用的地方有许多成分!=只是用那种肉去除成分但留下其他.....我怎么能解释多种成分。

select Recipe.name as "No chicken"  from Recipe inner join IngredientList on Recipe.recipeId=IngredientList.recipeId inner join Ingredients on IngredientList.IngredientId=Ingredients.ingredientId where type!="chcicken" group by Recipe.name;

3 个答案:

答案 0 :(得分:1)

原始语句的GROUP BY没有聚合函数。这没有意义。如果您尝试排序,它应该是ORDER BY

尝试这样的事情:

SELECT `Recipe`.`name` AS "No chicken"
FROM `Recipe`
WHERE `Recipe`.`RecipeId` NOT IN (
    SELECT DISTINCT `IngredientList`.`RecipeId` AS `RecipeID`
    FROM `IngredientList`
        INNER JOIN `Ingredients` ON `IngredientList`.`IngredientId` = `Ingredients`.`IngredientId`
    WHERE `Ingredients`.`Type` = 'chicken'
)
ORDER BY `Recipe`.`name`

根据您的架构,如果您获得重复的配方名称,则可能需要在主选择语句中使用SELECT DISTINCT

答案 1 :(得分:1)

上面有一些拼写错误,但Amirshk有一个逻辑上正确的答案。

但是,我建议避免使用MySQL中的IN()和NOT IN()子句,因为它们在一组像大型配方数据库那样大的表上非常非常慢。可以将IN和NOT IN重新编写为连接,以将运行时间缩短到MySQL 5.0中的1/100。即使MySQL 5.5有了很大的改进,等效的JOIN查询也会在大型表的基础上进行1/5的基准测试。

以下是修订后的查询:

SELECT
Recipe.name AS "No Chicken"
FROM Recipe LEFT JOIN
    (
    SELECT IngredientList.recipeId, Ingredients.ingredientId
    FROM IngredientList JOIN Ingredients USING (IngredientId)
    WHERE Ingredients.type = 'chicken'
    ) WithChicken
    ON Recipe.recipeId = WithChicken.recipeId
WHERE WithChicken.recipeId IS NULL;

这是非常迟钝的,所以这里是简化的SQL,它提供了NOT IN(...)等效排除连接的关键概念:

SELECT whatever FROM x
WHERE x.id NOT IN (
    SELECT id FROM y
};

变为

SELECT whatever FROM x
LEFT JOIN y ON x.id = y.id
WHERE y.id IS NULL;

答案 2 :(得分:0)

使用内部查询过滤鸡肉食谱,然后选择没有它们的所有食谱。

如此:

select
    Recipe.name as "No chicken"
    from Recipe
        inner join IngredientList on Recipe.recipeId=IngredientList.recipeId
        inner join Ingredients on IngredientList.IngredientId=Ingredients.ingredientId
    where Recipe.recipeId NOT IN (
        select
        Recipe.recipeId
        from Recipe
            inner join IngredientList on Recipe.recipeId=IngredientList.recipeId
            inner join Ingredients on IngredientList.IngredientId=Ingredients.ingredientId
            type ="chcicken" group by Recipe.recipeId)