如何使用sql仅选择大于0的值?

时间:2013-03-31 14:21:37

标签: php mysql sql

我有一个包含负值和正值的mysql表,我想只对正数值求和。

2 个答案:

答案 0 :(得分:5)

$sumQuery = "SELECT SUM(myNumber) AS 'mySum' FROM myTable WHERE myNumber > 0";
$rs = mysql_query($sumQuery);
$result = fetch_assoc($rs);
echo "My sum is: ".$result["mySum"];

正如Rekire指出的那样,应该避免使用mysql函数,你应该使用mysqli:

$query = "SELECT SUM(myNumber) AS 'mySum' FROM myTable WHERE myNumber > 0";

if ($result = $mysqli->query($query)) {

   /* fetch associative array */
   while ($row = $result->fetch_assoc()) {
      echo "My sum is: ".$row["mySum"];
   }

   /* free result set */
   $result->free();

}

直接来自http://www.php.net/manual/en/mysqli-result.fetch-assoc.php(我只修改了sql语句)

答案 1 :(得分:3)

SELECT SUM(number) as total from tblname WHERE number > 0

现在你可以使用总价值。