1

一.FIND_IN_SET

适用情况:

    在实际应用中,可能会出现这种情况:查找一个id是否在某个字段存储的字符串中,查找出一个列表。如:
    

clipboard.png
查找出所有含有6的记录,就可以这样查询(这里用的hinkphp):

举例

       if(!empty($arr)){
            //遍历出子subid并进行处理
            $length=count($arr);
            $str="";
            for($x=0; $x<=$length-1; $x++){
                $arr2[$x]=$arr[$x]['subid'];
                //拼接sql语句
                $str.=" or FIND_IN_SET(".$arr2[$x].",first_subject)";
                //裁掉前面的空格和or
                $res_str=substr($str,4);
            }
            $condition['check']=3;
            $condition['_string']=$res_str;
            $count=M("teacher")->where($condition)->count();
            $Page= new \Think\Page($count,1);
            $show= $Page->show();
            $teacher=M("teacher")->where($condition)->limit($Page->firstRow.','.$Page->listRows)->select();

主要用到的是的是 FIND_IN_SET(a,b),其中a是字符串,b是字段。

再来个例子:

        if(!empty(I("request.indentity"))){
           $condition['indentity']=I("request.indentity"); 
        }
        if(!empty(I("request.gender"))){
           $condition['gender']=I("request.gender"); 
        }
        if(!empty(I("request.school"))){
           $condition['school']=I("request.school");
        }
        if(!empty(I("request.subid"))){
            $condition['_string']="FIND_IN_SET(".I("request.subid").",first_subject)";
        }
        if(!empty(I("request.teach_place"))){
            $condition['_string']="FIND_IN_SET(".I("request.teach_place").",teach_place)";
        }
        if((!empty(I("request.teach_place")))&&(!empty(I("request.subid")))){
            $condition['_string']="FIND_IN_SET(".I("request.subid").",first_subject) and FIND_IN_SET(".I("request.teach_place").",teach_place)";
        }
        $condition['check']=3;
        
        

二.利用字符串字段,查找每个字符对应的相关表的数据

适用情况:

clipboard.png,某个字符串由多个id组成,如图,现在想遍历出字符串中包含的id对应相关表的记录。

举例:

这个例子中是二级遍历,用于显示老师列表中可教授科目的列表,要遍历数组,一个个取出

    //遍历已选取的课程数组,需要数组的组合  二级,需要两次遍历
    $arr_length=count($teacher);
    for($y=0; $y<=$arr_length-1; $y++){
        $subject_str=substr($teacher[$y]['first_subject'],0,-1);
        //字符串转成数组  subid的数组
        $subject_arr1=explode(",",$subject_str);
        $length=count($subject_arr1);
        //for循环利用subid查到课程,从而查到课程名,进而把subid和课程名组成二维数组
        for($x=0; $x<=$length-1; $x++){
            //查找课程名,一行记录的数组
            $subject_arr2[$x]=M("subject")->where(array("subid"=>$subject_arr1[$x]))->find();
            //课程名数组
            $subject_arr3[$y][$x]['subid']=$subject_arr2[$x]['subid'];
            $subject_arr3[$y][$x]['subject']=$subject_arr2[$x]['subject'];
        }
        
    }


李尚
61 声望3 粉丝