我希望我没有曲解我问题的解释:
我有一个有数百行的表,每一行都是一个含有营养信息的食谱,例如:
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 <> ''
如果我遗漏了什么,请告诉我
您可以使用连接来执行此操作。为了防止重复,您需要一个条件,其中配方id是有序的(这也可以防止一个配方出现三次):
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个组合中快速增长。