帮助优化SQL查询

时间:2011-01-06 20:47:21

标签: sql sqlite

我需要一些帮助来解决这个问题。 我正在使用Web应用程序和数据库我正在使用sqlite。有人可以帮我从数据库中查询一个必须优化的查询== fast =)

我有表x:

ID | ID_DISH | ID_INGREDIENT
 1 | 1       | 2
 2 | 1       | 3
 3 | 1       | 8
 4 | 1       | 12

 5 | 2       | 13
 6 | 2       | 5
 7 | 2       | 3

 8 | 3       | 5
 9 | 3       | 8
 10| 3       | 2

.... ID_DISH是不同菜肴的ID,ID_INGREDIENT是由以下菜肴组成的配料: 所以在我的情况下,id为1的菜肴是用含有2,3的成分制作的。

在此表中,a有超过15000行,我的问题是:

我需要查询,这将获取行,在那里我可以找到按照我的algoritem添加的ingitsients ASC的顺序排列的菜肴。

考试:foo(2,4) 将按此顺序排列:

ID_DISH | count(stillMissing)
    10  |   2
    1   |   3    

ID为10的菜具有id为2和4的成分,而且还没有2个,那么

我的查询是:

SELECT
    t2.ID_dish,
    (SELECT COUNT(*) as c FROM dishIngredient as t1
     WHERE t1.ID_ingredient NOT IN (2,4)
     AND t1.ID_dish = t2.ID_dish
     GROUP BY ID_dish) as c
FROM dishIngredient as t2
WHERE t2.ID_ingredient IN (2,4)
GROUP BY t2.ID_dish
ORDER BY c ASC

有效,但很慢......

2 个答案:

答案 0 :(得分:2)

select ID_DISH, sum(ID_INGREDIENT not in (2, 4)) stillMissing 
from x
group by ID_DISH
having stillMissing != count(*)
order by stillMissing 

这是解决方案,我以前的查询工作5 - 20s这项工作约80ms

答案 1 :(得分:1)

这是来自内存,因为我不知道sqlite的SQL方言。

SELECT DISTINCT T1.ID_DISH, COUNT(T1.ID_INGREDIENT) as COUNT
FROM dishIngredient as T1 LEFT JOIN dishIngredient as T2 
ON T1.ID_DISH = T2.ID_DISH
WHERE T2.ID_INGREDIENT IN (2,4)
GROUP BY T1.ID_DISH
ORDER BY T1.ID_DISH