2013-08-03 43 views
0

我想查询结果集到一个变量,然后使用该结果的另一个查询循环。通过mysql的临时表

所以现在我有几个类型的威士忌在我的成分表,我能找到的所有的人,并用:

CREATE TEMPORARY TABLE TempTable (Ingredient_Id int); 
Insert into TempTable Select Ingredient_Id from ingredients where INSTR(Ingredient_Name,'Whiskey')>0; 

这给了我所有我的ID,我需要。然后,我想获得有关数据:

select drink_names.*,ingredients.*, drink_recipes.* 
from drink_recipes 
Left JOIN drink_names ON drink_recipes.Drink_Id = drink_names.Drink_Id 
Left JOIN ingredients ON ingredients.Ingredient_Id = drink_recipes.Ingredient_Id 
where drink_recipes.Ingredient_Id in TempTable #This is the problem 
Order By Drink_Name 

我在如何与每个ID在TempTable

回答

1
select drink_names.*,ingredients.*, drink_recipes.* 
from drink_recipes 
Left JOIN drink_names ON drink_recipes.Drink_Id = drink_names.Drink_Id 
Left JOIN ingredients ON ingredients.Ingredient_Id = drink_recipes.Ingredient_Id 
where drink_recipes.Ingredient_Id in 
(
    Select Ingredient_Id 
    from ingredients 
    where INSTR(Ingredient_Name,'Whiskey')>0 
) 
Order By Drink_Name 

运行此查询或损失,你也可以尝试

select drink_names.*,ingredients.*, drink_recipes.* 
from drink_recipes 
Left JOIN drink_names ON drink_recipes.Drink_Id = drink_names.Drink_Id 
Left JOIN ingredients ON ingredients.Ingredient_Id = drink_recipes.Ingredient_Id 
         AND INSTR(ingredients.Ingredient_Name,'Whiskey') > 0 
Order By Drink_Name 
+0

不错!谢谢。甚至不需要临时表。 – Nick