我已經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
戈爾迪,我希望你能閱讀我的評論,因爲你'接受'你不應該使用的解決方案。當你的表增長很大時,這個查詢會變得越來越慢。 –