【问题标题】:Sqlite3 Subquery where ALL records in subquery are trueSqlite3 子查询,其中子查询中的所有记录都为真
【发布时间】:2023-03-18 00:43:01
【问题描述】:

我正在寻找一种解决方案,以防止我循环检查所有子记录是否符合要求的条件。

使用其他SQL语言,我可以使用ALL查询,但是sqlite不支持 "where field = ALL (select subquery)" 语法。

我有 3 张桌子。一,食谱清单。二、配方成分清单。三,用​​户将打开和关闭值以选择正确配方的表格。

我需要显示包含用户勾选的“所有”成分的所有食谱。

因此,如果用户选择“青椒”和“鸡肉”,则只会显示包含两者的食谱。

Table 1: Recipes
recipe_id   int
recipe_name text

Table 2: Ingredients
recipe_header     int ( link to header)
recipe_ingredient text

Table 3: User selection ( this table will be modified on the fly to represent only ingredients that are included in recipes as different ingredients are checked off)
recipe_ingredient   text
user_selected       text (true/false)

Table 1:
t1_id       t1_name
---------   ---------------
1       Chicken Marsala
2       Chicken Parmesan
3       Flank Steak
4       Grilled Salmon

Table 2:
t2_link     t2_ingredient
-------     -------------
1       chicken
1       green peppers
1       olive oil
2       chicken
2       olive oil
2       peeled tomatoes
3       flank steak
3       olive oil
3       soy sauce
3       pepper
4       salmon fillet
4       soy sauce
4       pepper

Table 3:
t3_ingredient       t3_checked
-------------       ----------
chicken         ( true or false )
flank steak     ( true or false )
green peppers       ( true or false )
olive oil       ( true or false )
peeled tomatoes     ( true or false )
pepper          ( true or false )
salmon fillet       ( true or false )
soy sauce       ( true or false )

如果用户选择以下成分(真) “鸡肉”、“橄榄油”

-- 将显示鸡肉马沙拉和鸡肉帕尔马干酪。

如果用户选择“酱油”和“辣椒”

-- 将显示牛腩和烤三文鱼。

如果用户选择“橄榄油”

-- 将显示鸡肉马沙拉、鸡肉帕尔马干酪和牛腩牛排。

【问题讨论】:

    标签: sql sqlite relational-division


    【解决方案1】:

    this SQL Fiddle 中演示的一种方法:

    select * from Table1
    where t1_id IN (
      SELECT t2_link 
      FROM Table2 INNER JOIN Table3 ON 
        t2_ingredient = t3_ingredient AND t3_checked = 'true'
      GROUP BY t2_link
      HAVING COUNT(DISTINCT t2_ingredient) = (
        SELECT COUNT(t3_ingredient) FROM Table3 WHERE t3_checked = 'true'
        )
    )
    

    “鸡”、“橄榄油”的搜索结果

    | t1_id |          t1_name |
    |-------|------------------|
    |     1 |  Chicken Marsala |
    |     2 | Chicken Parmesan |
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 2022-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多