mysql通过匹配固定位置的行和strlength()来获取数据

时间:2012-05-31 06:46:50

标签: php mysql

我有一个表格,其中一个字段包含滚动数字,如下所示:

   id | roll_no
   --------------
   1  | 290320452
   2  | 290320453
   3  | 290340454
   4  | 290330455

从上面的列我想要roll_no匹配位置4和5与32。 结果将是

   id | roll_no
   --------------
   1  | 290320452
   2  | 290320453

现在我通过过滤结果数组来完成:

    $subject_code = 32;    
    foreach($result as $row){
                    if($subject_code != NULL){
                        if(substr($row['roll_no'],3,2) == $subject_code){
                            $data[] = $row['roll_no'];
                        }
                    }
                    else{
                        $data[] = $row['roll_no'];
                    }
}

查询mysql查询时是否有更好的过滤方法。

我见过mysql的SUBSTRING()函数,但没有帮助。

2 个答案:

答案 0 :(得分:2)

select roll_no from your_table
where substring(cast(roll_no as char(11)), 4, 2) = '32'

答案 1 :(得分:1)

这个怎么样:
您可以使用_ (underscore)作为外卡来匹配确切的位置数。

select
 id, roll_no 
from
 roll_numbers_table
where
 roll_no like '___32%'; // 3 underscores before 32

关于样本数据的陈述将导致:

id | roll_no
--------------
1  | 290320452
2  | 290320453