SELECT BETWEEN的多维数组值 - PHP MYSQL

时间:2015-04-20 09:40:08

标签: php

您好基本上我的目标是获得总重量计数及其总和特定范围,例如:

0.1到0.5 0.6 - 1.0 1.01 - 1.50 ....等等......

因此,对于每个范围,我必须编写单独的选择查询?如下所示:

SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN 0.1 AND 0.5
SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN 0.6 AND 1.0
SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN 1.01 AND 1.5

它可能有许多范围,如上面的不固定。

因此我想要的结果如下:

0.1 - 0.5    = 3 / 9.4   - ( its total count / sum of weight )
0.6 - 1.0    = 2 / 4.5
1.01 - 1.5   = 0 / 0

... so on and on....

因此我教会将该范围保存在多维数组中并传递给for循环/中的每个选择查询,如下所示:

$info = array("0" =>array("a1"=>0.1,"a2"=>0.5),
              "1" => array("b1"=>0.6,"b2"=>1.0),
              "2" => array("c1"=>1.01,"c2"=>1.5),
              "3" => array("d1"=>1.51,"d2"=>2.0)
             );


echo"<table>";
 foreach($info as $row) {
  echo('<tr>');
  foreach($row as $cell) {
    echo('<td>' . $cell . '</td>');

   $sql = "SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN ".$cell." and ??????";

  }
  echo('</tr>');
} 
echo "</table>";

AS ITS在SELECT值中取每个单值,当我回显sql选择时,我看到8次选择查询,其中我应该只按照范围获得4个选择查询

我如何使用BETWEEN

如果有任何其他建议,请将结果告诉我:

0.1 - 0.5    = 3 / 9.4   - ( its total count / sum of weight )
0.6 - 1.0    = 2 / 4.5
1.01 - 1.5   = 0 / 0

... so on and on....

1 个答案:

答案 0 :(得分:2)

我建议改写你的foreach:

echo"<table>";
foreach($info as $row) {
    echo('<tr>');
    echo "<td>SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN ".implode(' and ', $row) . "</td>";
    echo('</tr>');
}
echo "</table>";

implode会将数组的元素组合成一个字符串,每个数组元素之间带有单词and

例如:

array("a1"=>0.1,"a2"=>0.5)

变为:

0.1 and 0.5

以上输出为:

SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN 0.1 and 0.5
SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN 0.6 and 1
SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN 1.01 and 1.5
SELECT count(*),sum(wght) FROM PROD WHERE wght BETWEEN 1.51 and 2