问题:
mysql的in条件查询,是括号里拼接逗号相隔的字串,这个字长里的个数还有限制,网上的说法是1000个,为了避免超出该范围,可专门封装一个方法
一般解决方式:
1.使用exists写法替代in写法,exists写法是使用条件查询替代in写法里的一长串字串,这个有时候没法使用,比如使用第三方接口查学校一年级2千个学生的考试成绩,你只知道这些学生的id,没有更多的关联条件
2.使用or的写法,将in条件过长的字串拆开,mysql支持以下写法:
select * from table_name where user_id in(1,2,3) or user_id in(4,5,6)
方法封装:
/*
* $ziduan_name string 字段名称:user_id1
* $data_str string in条件一长串字串:1,2,3,4,....1001,1002
* $fenduan_num int 小于1000的数值,将原先过长的字段分段
*/
public static function sql_in_where($ziduan_name,$data_str,$fenduan_num=500){
$where = '';
$data_arr = explode(',',$data_str);
//总个数
$count_num = count($data_arr);
if( $count_num <= $fenduan_num ){
//in条件正常写
$where = $ziduan_name.' in('.$data_str.') ';
}else{
//in条件中数目过多的需要拆成几份,使用or拼接sql条件语句
$i_count = ceil($count_num/$fenduan_num); //拆成总份数
$tmp_data_arr = array_chunk($data_arr,$fenduan_num);
for( $i = 0;$i< $i_count;$i++ ){
$tmp_val_str = '';
foreach( $tmp_data_arr[$i] as $val ){
$tmp_val_str .= $val.',';
}
$tmp_val_str = trim($tmp_val_str,',');
//用于拼接的 or
if( $i == $i_count -1 ){
//最后的一个不需要 or
$is_or = " ";
}else{
$is_or = " OR ";
}
$where .= $ziduan_name." in(".$tmp_val_str.") ".$is_or;
}
//给where条件加上括号
$where = " ( ".$where.") ";
}
return $where;
}
测试效果:
$new_student_id_str = "12,13,14,15,16,17,18,19";
$sql_in_where = self::sql_in_where('s.student_id',$new_student_id_str,3);
echo $sql_in_where;
//( s.student_id in(12,13,14) OR s.student_id in(15,16,17) OR s.student_id in(18,19) )