更新时间:2023-02-03 23:11:39
您似乎有一个配方表,其中包含用逗号分隔的成分列表:
You seem to have a recipe table that contains comma separated list of ingredients:
5,2,1,6,2,3,45
以及给定成分的列表:
1,2,3,4,5,6
您想找到可以使用给定成分准备的食谱(食谱成分是给定成分的子集).您需要编写构建以下查询的PHP代码:
And you want to find recipes that could be prepared with the given ingredients (recipe ingredients is a subset of given ingredients). You need to write PHP code that builds the following query:
SELECT *
FROM recipe
WHERE (
FIND_IN_SET('1', rcring) > 0 AND
FIND_IN_SET('2', rcring) > 0 AND
FIND_IN_SET('3', rcring) > 0 AND
FIND_IN_SET('4', rcring) > 0 AND
FIND_IN_SET('5', rcring) > 0 AND
FIND_IN_SET('6', rcring) > 0
)
基于您的尝试的PHP代码的粗略概述(您必须将其转换为准备好的语句):
A rough outline of the PHP code based on your attempt (which you must convert to prepared statements):
$conditions = [];
foreach($fridge_ingredients as $ingredient) {
$conditions[] = sprintf("FIND_IN_SET('%d', rcring) > 0", $ingredient);
}
$query = sprintf("SELECT *
FROM recipe
WHERE (%s)", implode(" AND ", $conditions));
话虽如此,正确的解决方案是规范化您的数据.这是结构的概述:
Having said that, the correct solution is to normalize your data. Here is an outline of the structure:
CREATE TABLE recipe (recipeid INT NOT NULL PRIMARY KEY, name VARCHAR(100));
CREATE TABLE ingredient (ingredientid INT NOT NULL PRIMARY KEY, name VARCHAR(100));
CREATE TABLE recipe_ingredient(recipeid INT NOT NULL,ingredientid INT NOT NULL, PRIMARY KEY(recipeid, ingredientid));
INSERT INTO recipe VALUES
(1, 'recipe 1'),
(2, 'recipe 2'),
(3, 'recipe 3'),
(4, 'recipe 4');
INSERT INTO ingredient VALUES
(1, 'ingredient 1'),
(2, 'ingredient 2'),
(3, 'ingredient 3'),
(4, 'ingredient 4');
INSERT INTO recipe_ingredient VALUES
(1, 1),
(2, 1), (2, 2),
(3, 1), (3, 2), (3, 3),
(4, 1), (4, 2), (4, 3), (4, 4);
查询:
SELECT *
FROM recipe
WHERE recipeid IN (
SELECT recipeid
FROM recipe_ingredient
GROUP BY recipeid
HAVING COUNT(CASE WHEN ingredientid IN (1, 2, 3) THEN 1 END) = COUNT(*)
)
结果:
recipeid | name
----------+----------
1 | recipe 1
2 | recipe 2
3 | recipe 3