给定SELECT语句,我想通过多个子查询得到结果RECIPE_ID?

时间:2015-02-18 06:08:50

标签: php mysql

我有ingredientingredientId是709,710,711这个ID我被放入成分子查询中AS match_percentage我怀疑(3*100 / count正在计算ingredientingredientId,这些都来自我的PHP代码,我给出了我的解决方案的示例。

现在结果就像那些RECIPE_ID我传递了三个ingredientingredientId与此表recipe_ingredient匹配。ingredientId并保持recipe_ingredient }。recipeId

我想要RECIPE_ID |结果为1和3。只有世界卫生组织有三个ID 709,710,711甚至不是两个709,710。

这是我的RECIPE_ID查询:

SELECT 
    `recipe`.`recipeId` AS recipe_id ,
    (select count(`recipe_ingredient`.ingredientId) from `recipe_ingredient` where `recipe`.recipeId = `recipe_ingredient`.recipeId) as ingredientCount ,  
    IF(
        (select (3*100 / count(DISTINCT `recipe_ingredient`.ingredientId)) from `recipe_ingredient` where `recipe_ingredient`.recipeId = `recipe`.recipeId)>99                      
        ,100
        ,round( (select (3*100 / count(DISTINCT `recipe_ingredient`.ingredientId)) from `recipe_ingredient` where `recipe_ingredient`.recipeId = `recipe`.recipeId) ) 
    ) 
    as match_percentage , 
    GROUP_CONCAT(
        DISTINCT `recipe_ingredient`.ingredientId 
        ORDER BY `recipe_ingredient`.ingredientId ASC 
           ) as recipeIngredients 
from `recipe` 
left join `recipe_ingredient` on `recipe_ingredient`.recipeId = `recipe`.recipeId
left join `ingredient` on `ingredient`.ingredientId = `recipe_ingredient`.ingredientId   
where  `recipe`.`recipeId` IN( 
                SELECT 
                `recipe_ingredient`.`recipeId`
                FROM `recipe_ingredient` 
                WHERE `recipe_ingredient`.`ingredientId` 
                IN(
                  SELECT `ingredient`.`ingredientId` AS linkIng 
                  FROM `ingredient` 
                  WHERE `ingredient`.`ingredientId` IN(709,710,711) or `ingredient`.`linkIngredientPerent` IN(709,710,711)
                )
                GROUP BY `recipe_ingredient`.`recipeId` 
                ORDER BY `recipe_ingredient`.`recipeId` ASC
              )  

and (select (3*100 / count(DISTINCT `recipe_ingredient`.ingredientId)) from `recipe_ingredient` where `recipe_ingredient`.recipeId = `recipe`.recipeId) > 24  
group by `recipe`.recipeId 

我的查询链接:http://sqlfiddle.com/#!2/f4983/2

1 个答案:

答案 0 :(得分:2)

这是你想要的吗?请用其他方案检查。

http://sqlfiddle.com/#!2/f4983/8