나는 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"
$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).')');
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
NB : 아래 단의 의견에 따라, 인덱스를 사용하지 않고이 쿼리가 큰 테이블에 속도가 느릴 수 있습니다. 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
}
엘리먼트를 이스케이프 처리하려면, mysql_real_escape_string을 사용하십시오. –
필요 없음 – delphist
골디, 당신이 당신이 실제로 사용해서는 안됩니다 솔루션을 '접수'당신이 내 의견을 읽을 수 있기를 바랍니다. 테이블이 커지면 쿼리가 점점 느려질 것입니다. –