我希望我对我的问题的解释不是很糟糕:
我有一个有数百行的表,每一行都是一个包含营养信息的食谱,例如:
recipe_table:
id | calories | protein| carbs | fat
recipe1, 100, 20g, 10g, 2g
recipe2, 110, 10g, 12g, 12g
recipe3, 240, 20g, 1g, 23g
....我需要创建一个新的表(recipe_index),它将recipe_table中每个食谱的每种可能组合显示为一组3,因此它看起来如下所示:
recipe_index:
id1 | id2 | id3 |calories| protein | carbs | fat
recipe1, recipe2, recipe3, 450, 50g, 23g, 37g
....基本上,它允许我查询recipe_index并说“哪3种食谱组合的总值在440卡路里和460卡路里之间”
我目前的代码在3次用餐时可以正常工作,但是我最终在recipe_index中有大约450,000条记录,我还需要在4次、5次和6次用餐中做同样的事情,所以我在结束时计算了数百万条记录。有没有更有效的方法来做到这一点?也许我需要考虑为每个范围划分一个表?
我当前的SQL代码:
INSERT INTO recipe_index
SELECT distinct '3' as nummeals, t1.id as id1, t2.id as id2, t3.id as id3, 0 as id4,
t1.calories_ps+t2.calories_ps+t3.calories_ps as calories, t1.protein_ps+t2.protein_ps+t3.protein_ps as
protein, t1.carbohydrate_ps+t2.carbohydrate_ps+t3.carbohydrate_ps as carbohydrate,
t1.fat_ps+t2.fat_ps+t3.fat_ps as fat from recipes t1 inner join recipes t2 on t1.Id < t2.Id inner join recipes t3 on t2.Id < t3.Id WHERE t1.image <> '' AND t2.image <> '' AND t3.image <> ''如果我遗漏了什么明显的东西,请告诉我
发布于 2013-05-31 02:44:34
您可以使用join来完成此操作。为了防止重复,您需要一个配方In按顺序排列的条件(这也可以防止一个配方出现三次):
select r1.id, r2.id, r3.id,
(r1.calories + r2.calories + r3.calories) as calories,
(r1.protein + r2.protein + r3.protein) as protein,
(r1.carbs + r2.carbs + r3.carbs) as carbs,
(r1.fat + r2.fat + r3.fat) as calories
from recipe_table r1 join
recipe_table r2
where r1.id < r2.id join
recipe_table r3
where r2.id < r3.id;与查询的唯一区别是distinct不是必需的,因为排序可以防止重复。
你面临的问题是有很多的组合。所以有4种食谱的数百万种组合。我猜你是从77个食谱开始的。其中4个组合的数量是77*76*75*74 --这个序列将在5到6个组合中快速增长。
https://stackoverflow.com/questions/16843598
复制相似问题