Mysql循环通过临时表

时间:2013-08-03 18:22:10

标签: mysql

我正在尝试将查询结果设置为变量,然后将该结果用于另一个查询。

所以现在我在我的食材表中有几种类型的威士忌,我可以找到它们所有的和:

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

这给了我所有我需要的身份证明。然后我试图获得相关数据:

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

我无法使用TempTable

中的每个ID运行此查询

1 个答案:

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