MYSQL - 获取其多对多关系包含所有术语的实体

MYSQL - Fetching entities whose many-to-many relationship contains all terms collectively

我正在使用以下数据库模式

create table Recipe (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(25), 
    description VARCHAR(50), 
    instructions VARCHAR(500)) 
    ENGINE=InnoDB DEFAULT CHARSET=utf8;

create table Ingredient (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(50)) 

create table Measure (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
    name VARCHAR(30)) 

create table RecipeIngredient (recipe_id INT NOT NULL, 
    ingredient_id INT NOT NULL, 
    measure_id INT, 
    amount INT, 
    CONSTRAINT fk_recipe FOREIGN KEY(recipe_id) REFERENCES Recipe(id), 
    CONSTRAINT fk_ingredient FOREIGN KEY(ingredient_id) REFERENCES Ingredient(id), 
    CONSTRAINT fk_measure FOREIGN KEY(measure_id) REFERENCES Measure(id)) 

并使用类似这样的东西添加 data/query 它

INSERT INTO Measure (name) VALUES('CUP'), ('TEASPOON'), ('TABLESPOON');

INSERT INTO Ingredient (name) VALUES('egg'), ('salt'), ('sugar'), ('chocolate'), ('vanilla extract'), ('flour');

INSERT INTO Recipe (name, description, instructions) VALUES('Chocolate Cake', 'Yummy cake', 'Add eggs, flour, chocolate to pan. Bake at 350 for 1 hour');


INSERT INTO RecipeIngredient (recipe_id, ingredient_id, measure_id, amount)  VALUES (1, 1, NULL, 3);

INSERT INTO RecipeIngredient (recipe_id, ingredient_id, measure_id, amount)  VALUES (1, 2, 2, 1);

INSERT INTO RecipeIngredient (recipe_id, ingredient_id, measure_id, amount)  VALUES (1, 3, 1, 2);

INSERT INTO RecipeIngredient (recipe_id, ingredient_id, measure_id, amount)  VALUES (1, 4, 1, 1);

SELECT r.name AS 'Recipe', 
    ri.amount AS 'Amount', 
    mu.name AS 'Unit', 
    i.name AS 'Ingredient' 
FROM Recipe r 
JOIN RecipeIngredient ri on r.id = ri.recipe_id 
JOIN Ingredient i on i.id = ri.ingredient_id 
LEFT OUTER JOIN Measure mu on mu.id = measure_id;

哪个return

Recipe              | Amount    | Unit     | ingredient
Chocolate Cake      | 3         |null      | egg
Chocolate Cake      | 1         |TEASPOON  | salt
Chocolate Cake      | 2         |CUP       | sugar
Chocolate Cake      | 1         |CU        | chocolate

我如何return 食谱中的成分是所提供成分列表的子集?

例如,如果提供列表(鸡蛋、盐、糖),我不应该 return 巧克力蛋糕。 但是,如果提供(鸡蛋、盐、火腿、奶酪、糖、香肠、巧克力),我应该 return 巧克力蛋糕。

您可以使用聚合和 having 子句:

SELECT r.name recipe
FROM Recipe r 
JOIN RecipeIngredient ri on r.id = ri.recipe_id 
JOIN Ingredient i on i.id = ri.ingredient_id 
GROUP BY r.id, r.name
HAVING MAX(i.name NOT IN ('egg', 'salt', 'sugar')) = 0

您可以控制元素,成分应该是 IN 条件的右操作数中的值列表的子集。

提示

SELECT ingredient AS what_you_are_missing
    FROM  RecipeIngredient
    WHERE Recipe = 'Chocolate cake'
      AND NOT FIND_IN_SET(ingredient, "egg,salt,sugar") )

或者...如果可能的成分列表足够小,那么 SETBIGINT UNSIGNED 可以用于 AND 和 OR 等来操纵“集合”操作。