2

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

4

2 回答 2

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-functions,而应该使用 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 语句)

于 2013-03-31T14:22:50.663 回答
4
SELECT SUM(number) as total from tblname WHERE number > 0

现在您可以使用总值。

于 2013-03-31T14:24:47.463 回答