SQL - 使用子查询的结果

时间:2012-12-05 00:57:20

标签: android sql json sqlite

我的SQLLite数据库中有两个表。我正在尝试取回可以使用输入的成分制作的饮料。

我正在尝试制定此查询以获得我想要的内容。

餐饮

  

drink_id |标题|成分|方向| ingredientsNum

示例行看起来像

  

1 | Papa Smurf | 1压碎蓝色冰棒,8盎司Kool-Aid,4盎司伏特加酒|方向| 3

表格成分

  

drink_id |成分

示例行看起来像

  

1 |蓝色冰棒

我的查询

这是我想要返回的部分伪代码(在我得到这个之后,我将动态地用于查询)。

我希望所有输入量等于或大于饮料成分的饮料都返回,并且那些输入的成分与饮料中所需的所有成分相匹配。

SELECT drinks.title, drinks.ingredients, drinks.directions
FROM drinks, (SELECT count(ingredients._id) as ingredientNumber FROM ingredients
WHERE ingredients.ingredient LIKE '%rum%'
GROUP BY ingredients._id) as foundIngredients
WHERE drinks.ingredientsNum = foundIngredients.ingredientNumber;

任何人都可以帮助我获得最合适的查询,甚至可以给我一些关于重构数据库模型的提示吗?我刚从一个80k行的长JSON文件中创建了这个数据库。

2 个答案:

答案 0 :(得分:1)

您的架构有点奇怪,因为通常您可能会使用3个表来真正规范化此数据结构(饮料,配料,饮料成分或类似物)。但是,由于您正在进行文本搜索,并且您已经在饮料表中拥有所有成分名称,因此您只需查询饮料表:

SELECT title, ingredients, directions
FROM drinks
WHERE ingredients LIKE '%rum%'
AND ingredients LIKE '%vodka%'
... // add more ingredients as needed 

确保您在配料领域有一个索引。请注意,如果您想要使用朗姆酒和/或伏特加酒返回所有饮品,则可以将AND更改为OR

答案 1 :(得分:1)

反映澄清问题的查询:

SELECT drinks.title, drinks.ingredients, drinks.directions
FROM drinks
WHERE drinks.ingredientsNum = (
    SELECT count(*)
    FROM ingredients
    WHERE (
        ingredients.ingredient LIKE '%rum%'
        OR ingredients.ingredient LIKE '%coke%'
        OR ingredients.ingredient LIKE '%vodka%'
        -- the same goes for each ingredient
    )
    AND ingredients.drink_id = drinks.drink_id
)

同样,如果您允许饮料除了所有指定的之外还有其他成分

SELECT drinks.title, drinks.ingredients, drinks.directions
FROM drinks
WHERE drinks.ingredientsNum >= [number of input ingredients]
AND [number of input ingredients] <= (
    SELECT count(*)
    FROM ingredients
    WHERE (
        ingredients.ingredient LIKE '%rum%'
        OR ingredients.ingredient LIKE '%coke%'
        OR ingredients.ingredient LIKE '%vodka%'
        -- the same goes for each ingredient
    )
    AND ingredients.drink_id = drinks.drink_id
)