我已经1个MySQL表称为颜色与行ID和名Mysql的搜索用逗号分隔的字符串
1 - yellow 2 - black 3 - red 4 - green 5 - white 6 - blue
我怎样才能获得ID的数组,如果我有,例如,搜索字符串
["colors"]=> string(14) "blue,red,white"
我已经1个MySQL表称为颜色与行ID和名Mysql的搜索用逗号分隔的字符串
1 - yellow 2 - black 3 - red 4 - green 5 - white 6 - blue
我怎样才能获得ID的数组,如果我有,例如,搜索字符串
["colors"]=> string(14) "blue,red,white"
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
select id from tab where find_in_set(name, '$colors') > 0
注:按以下丹的评论,此查询不使用索引,将是一个大的表慢。带有IN的查询更好:
select id from tab where name IN ('blue', 'red', 'white')
此查询可以使用名称列上的索引吗? –
优雅的解决方案,+1 – delphist
答案是否定的,索引不能使用,所以虽然它更短,但在工程意义上并不优雅。一个'='或'IN'比较是一个更好的查询。 –
$array = explode(",", $colors);
$search = impode("', '". $array);
$sql = "
SELECT
id,
name
FROM
colors
WHERE
name IN ('$search')
";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
//do something with the matches
}
试试这个
$colors = "blue,red,white";
// Exploding string to array
$colors = explode($colors, ',');
$colors_list = array();
foreach($colors as &$color)
{
// Escaping every element
$colors_list[] = "'".mysql_real_escape_string($color)."'";
}
// Executing the query
$query = mysql_query('SELECT `id` FROM `colors` WHERE `name` IN ('.implode(', ', $colors_list).')');
如果您要逃避元素,请使用'mysql_real_escape_string'来完成,而不是您自己的非等价代码。 –
这不是必需的 – delphist
戈尔迪,我希望你能阅读我的评论,因为你'接受'你不应该使用的解决方案。当你的表增长很大时,这个查询会变得越来越慢。 –