从数据数组中计算和搜索字符串

时间:2010-07-29 07:10:37

标签: php mysql regex

我有一个数据库表如下:

line     model        serial     range serial    
fa01     kd-g335ud   105x0001    105x0001-105x0200
fa01     kd-g335ud   105x0002    105x0001-105x0200 
fa01     kd-g335ud   105x0003    105x0001-105x0200 
fa02     kd-r311ed   105x0001    105x0001-105x0500
fa02     kd-r311ed   105x0002    105x0001-105x0500

当我查询它时,我希望结果如下:

line     model       qty        qty range
fa01     kd-g335ud   3            200
fa02     kd-r311ed   2            500

我写了以下查询,但是我仍然对如何显示数量范围感到困惑。

 //this just show until qty
    SELECT line, model, COUNT(serial) as qty FROM inspection GROUP BY line, model

    //this for search string
    $sql_result=array(//what must i fill?);
    foreach($sql_result as $row)
    {
       preg_match_all('/\d{4}/',$row,$matches);
       echo intval($matches[0][1])-intval($matches[0][0])+1;
    }

请帮助,因为我仍然不确定第二种语法

1 个答案:

答案 0 :(得分:1)

假设qty范围是range_serial

的最后三个字符
SELECT line, 
       model, 
       COUNT(serial) as qty,
       RIGHT(range_serial,3) as qty_range 
  FROM inspection 
 GROUP BY line, 
          model,
          range_serial

修改

$sqlQuery = 'SELECT line, model, COUNT(serial) as qty,range_serial as qty_range 
               FROM inspection 
              GROUP BY line, model, range_serial';

$sqlResult = mysql_query($sqlQuery); 

while ($row = mysql_fetch_assoc($sqlResult)) {
   preg_match_all('/\d{4}/',$row['qty_range'],$matches); 
   echo intval($matches[0][1])-intval($matches[0][0])+1; 
}