douhuang3833 2015-01-01 17:04
浏览 26
已采纳

从定义的子集中搜索列中的所有值组合

I have a table with the following schema in MySQL

Recipe_Quantity_ID,Recipe_ID, Recipe_Quantity, Ingredients_ID, Ingredient_Measurement_ID

The sample data can be found in this SQL Fiddle http://sqlfiddle.com/#!2/d05fe .

I want to search the table for the given (one or many) Ingredients_ID and return the Recipe_ID that has this Ingredients_ID

I do this by using this SQL

select Recipe_ID 
from   recipe_quantity
group by Recipe_ID 
having count(*) = {$ar_rows} 
and    sum(Ingredients_ID in ({$ids})) = {$ar_rows}

which may translate to

select Recipe_ID 
from   recipe_quantity 
group by Recipe_ID 
having count(*) = 4 
and    sum(Ingredients_ID in (8,5,45,88)) = 4

For searching for less Ingredients_ID I substract the last ID until I reach one Ingredient ID. By using this technique of course is not possible to search for all the combinations. Eg 8,5,45,85 | 8,45,85 | 45,85 | 5,45,85 etc.

Any ideas how I can search for all the combinations that may be true? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • douzhang3356 2015-01-01 18:27
    关注

    My understanding is that you want to get all recipes where you already have all the ingredients you need. you don't need to use all the ingredients you have but you don't want to have to go shopping.

    Correct me if I am wrong but I don't think there is a recipe that fits your ingredients list so I have used other ingredients. note that ingredients 13,36 wont be used.

    you should be able to put another select statement in the brackets that gets the ingredients that you have (select ingredients_id from ingredients_owned) it isn't good to specify them each time.

    select distinct c.Recipe_id
    from
      (select Recipe_ID
      from recipe_quantity 
      where Ingredients_ID in (5,6,1,11,8,12,13,36, 81,82,62,73,35)) c
      left join (select Recipe_ID
                  from   recipe_quantity 
                  where Ingredients_ID not in (5,6,1,11,8,12,13,36, 81,82,62,73,35)) x
        on c.Recipe_id = x.Recipe_id
    where x.Recipe_id is null
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法