我有一个数组$arr,长度不定,其取值可能为$arr=(1,5,7);也可能为$arr=(2,8,7,6,3,9)等等。
我有一sql语句为:select * from table where bianhao in $arr;
其中bianhao为表中一个字段,是编号。用in 的话速度较慢。我怎么才能在所有的情况下写成如下形式:
select * from table where bianhao = 1 or bianhao = 5 or bianhao = 7;
select * from table where bianhao = 2 or bianhao = 8 or bianhao = 7 or bianhao = 6 or bianhao = 3 or bianhao = 9;
我有一sql语句为:select * from table where bianhao in $arr;
其中bianhao为表中一个字段,是编号。用in 的话速度较慢。我怎么才能在所有的情况下写成如下形式:
select * from table where bianhao = 1 or bianhao = 5 or bianhao = 7;
select * from table where bianhao = 2 or bianhao = 8 or bianhao = 7 or bianhao = 6 or bianhao = 3 or bianhao = 9;
in不一定比or的写法慢.
$arr2 = array(2,8,7,6,3,9);function bianhao($arr,$keyName='bianhao')
{
if(!count($arr)) return;
return implode(' OR ',array_map(create_function('$i','return "'.$keyName.'=\'$i\'";'),$arr));
}
echo bianhao($arr);
echo "<br/>";
echo bianhao($arr2);
手册上写的
你的in后的(1,2,3)均为常量
要是in的可选项较少的话 速度方面应该不会有很大影响
如果你一定要用or 的话,代码这样写 就可以了。
$where = ' where bianhao = '.implode(' or bianhao = ', $arr);
$sql = 'select * from table '.$where;这样就OK了