我有一个颜色数组,想要匹配MYSQL中的颜色行,
只要颜色行与数组中的一种颜色匹配,就将其取出。
以下$colorArray
应与ID 2& 3,因为那些行包含黄色&蓝色
$colorArray = array('yellow','blue');
+------+---------+------------+
| id | product | color |
+------+---------+------------+
| 1 | tShirt | red,green |
| 2 | jeans | yellow,red |
| 3 | shorts | black,blue |
+------+---------+------------+
我只想要一个MySQL SELECT语法,我知道可以用PHP array_intersect
完成一些过滤器,但我不想出于某些原因。
有可能吗?
答案 0 :(得分:1)
我认为您在组合in
和Like %S%
方面存在问题,所以
REGEXP可能效率更高,但您必须对其进行基准测试,例如。
$colorsStr = implode('|', $colorArray); // => 'yellow|blue'
$sql = "SELECT * FROM <your_table_name> WHERE REGEXP '" . $colorsStr . "'";
答案 1 :(得分:1)
很容易:
<?php
$color = array('yellow', 'red');
$query = "";
foreach($color as $c)
$query .= "color like '%".$c."%' or ";
$sql = "SELECT * FROM <your_table_name> WHERE ".$query." 1=0";
?>
答案 2 :(得分:0)
试试这段代码:
$colorsStr = implode(',', $colorArray); // => 'yellow,blue'
$sql = 'SELECT id FROM <your_table_name> WHERE color IN('.$colorsStr.')';
答案 3 :(得分:0)
您可以尝试以下内容:
$colorArray = array('yellow','blue');
$colors = join(',',$colorArray);
$sql = "SELECT '$colors' AS colors,
color,
CONCAT('(', REPLACE(color, ',', '(\\,|$)|'), '(\\,|$))') AS regex,
'$colors' REGEXP CONCAT('(', REPLACE(color, ',', '(\\,|$)|'), '(\\,|$))') AS intersect
FROM YourTableName
GROUP BY id HAVING intersect > 0";
答案 4 :(得分:0)
$colorArray = array('yellow','blue');
$colors = implode(",",$colorArray);
$query = "SELECT color FROM TableName WHERE color = '.$colors.'";
答案 5 :(得分:0)
在查询中使用FIND_IN_SET()。试试这个让我知道。我希望我解决你的问题 您所需的查询
SELECT * FROM t3 WHERE FIND_IN_SET('yellow', colour) or FIND_IN_SET('blue', colour)
代码:
<?php
$colorArray = array('yellow','blue','red');
$where1 ="FIND_IN_SET('$colorArray[0]', colour) ";
$where="";
for($i=1;$i<sizeof($colorArray);$i++){
$color=$colorArray[$i];
$where .= " or FIND_IN_SET('$color', colour) ";
}
$sql="SELECT * FROM t3 WHERE $where1 $where";
//echo $sql;//SELECT * FROM t3 WHERE FIND_IN_SET('yellow', colour) or FIND_IN_SET('blue', colour) or FIND_IN_SET('red', colour)
// try running this query
?>