Sum Mysql表的列值

时间:2014-08-04 05:31:43

标签: php mysql

我有一个表名订阅者。有两个列名称为Hours和NewHr,这两列中有大量数据。我想减去Hours列和NewHr列的总值。这里我使用以下代码。但它只从列中减去NewHr的Hours和First值的第一个值。

$Uid=mysql_fetch_array(mysql_query("SELECT * FROM subscriber WHERE    Uid='$_SESSION[UniqId]'"));
$first_number = ($Uid['Hours']);
$second_number = ($Uid['NewHr']);     
$Balance_total = $first_number - $second_number;

请告诉我我将在$ first_number = _ 和$ second_number = ______ 中替换哪些代码来减去总列值。

2 个答案:

答案 0 :(得分:0)

根据您提供此查询的数据,我们应该完成这项工作:

SELECT 
  SUM(Hours) - SUM(NewHr)
  FROM subscriber 
  WHERE    Uid='$_SESSION[UniqId]'

答案 1 :(得分:0)

如果您想要总数的差异,那么您可以使用查询本身这样做

$result =mysql_fetch_array(mysql_query("SELECT SUM(Newhr) - SUM(Hours) as difference FROM subscriber WHERE Uid='$_SESSION[UniqId]'"));
$Balance_total = $result['difference'];