我有一张包含一些成分的表格。示例:
id | title | ingredients
1 | ex1 | ketchup, chicken, salt, honey, mountain dew
2 | ex2 | beef, pepper, chili, honey, salt
当用户搜索成分时,例如:
ketchup, salt, honey
我生成一个 sql 查询:
select * from recipes where(
(ingredients LIKE '%ketchup%')
AND (ingredients LIKE '%salt%')
AND (ingredients LIKE '%honey%')
它返回包含这些特定成分的所有食谱,并且它是灰色的。
现在。我添加了一个范围 slider ,用于选择输入的成分中有多少应该与搜索匹配以返回任何内容。可以说我选择至少应该匹配 2 种成分,我想制作一个 PHP 函数来输出一个 sql 字符串,该字符串将每个输入的成分配对,但我根本没有这种心态。 示例:
(ingredients LIKE '%ketchup%') AND (ingredients LIKE '%salt%')
OR
(ingredients LIKE '%ketchup%') AND (ingredients LIKE '%honey%')
OR
So on. So ketchup & salt pair, ketchup & honey pair, salt & honey pair.
当然还有变量,因此对输入的成分没有限制。我已经尝试了几个小时但没有成功。希望我已经清楚地解释了自己,并且有人能够帮助或教我一些东西:-)
我的执行当前字符串的 php 函数如下所示:
$c_soeg = "ketchup, whatever, whatever. etc";
$c_ing_arr = explode(",", $c_soeg);
$c_count_arr = count($c_ing_arr);
$i = 0;
$c_sql = "SELECT * FROM recipes WHERE (";
while($i < $c_count_arr){
$c_sql .= "(ingredients LIKE '%".trim($c_ing_arr[$i])."%')";
if($i != $c_count_arr-1){
$c_sql .= " AND ";
}
$i++;
}
$c_sql .= ")";
包含范围值的变量被命名为
$c_range;
最佳答案
代替 AND 和 OR 条件计算满足的条件。此示例为您提供至少两种成分匹配的所有记录:
select * from recipes
where
case when ingredients like '%ketchup%' then 1 else 0 end
+
case when ingredients like '%salt%' then 1 else 0 end
+
case when ingredients like '%honey%' then 1 else 0 end
> = 2;
关于php - 在sql表中搜索多个值,范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23061892/