sqlite - 查找可以由一组成分制成的食谱

标签 sql sqlite relational-database tagging

现在我在 ios 应用程序中使用 sqlite,我希望能够搜索可以从成分列表中制作的食谱(即,作为所提供成分的子集的食谱)

例如:

Recipe 1: A B C
Recipe 2: A B
Recipe 3: C D
Recipe 4: A
Recipe 5: E

Query for ingredients A B C returns recipes {1, 2, 4}
Query for ingredients A B returns recipes {2, 4}
Query for ingredients D returns {}

目前我设置的是

Table Items
name text primary key

Table Recipes
ID required_item integer, recipe_name text

我可以很容易地查询包含这三种成分中的任何一种的食谱和包含所有这三种成分的食谱,但我一直无法弄清楚如何只查询

Recipes ∈ P(Ingredients)

抱歉,我是数据库编程的新手,非常感谢任何帮助

最佳答案

您可以对搜索表使用左联接。然后 group by 食谱。使用 having 子句来要求对于每个食谱,没有不在搜索列表中的配料。例如:

select  ri.RecipeNr
from    RecipeIngredients ri
left join
        (
        select  'A' as Ingredient
        union all
        select  'B'
        union all
        select  'C'
        ) search
on      ri.Ingredient = search.Ingredient
group by
        ri.RecipeNr
having  count(case when search.Ingredient is null then 1 end) = 0

Live example at SQL Fiddle.

关于sqlite - 查找可以由一组成分制成的食谱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066631/

相关文章:

c# - 如何将两个表连接成一个新表以在 C# 中显示?

php - 使用 if 语句检查记录是否存在 mysql/php

ios - NSPredicate ALL 与 SQLite 存储的聚合

database - 如何在 Google AppEngine 上使用 JDBC

Sql 查询选择不在另一组中的所有行

sql - 计算直到某个日期的唯一组合 - 每月

c# - SQLite.Net - 不知道 System.Collections.Generic.List 错误 - Xamarin Android

iphone - iphone编程如何向sqlite数据库插入多行数据

sql - 关系索引数据库包装器

database - 是否所有具有部分依赖关系的关系模式都不在 3NF 中?