在smarty模板系统中使用PHP从数据库中获取SUM

时间:2014-03-02 18:44:17

标签: php mysql sql database smarty

以下是我目前正在使用的代码:

   $result = mysql_query("
SELECT SUM(s.amount) 
  FROM tblaffiliatespending s
  JOIN tblaffiliatesaccounts a
    ON a.id=s.affaccid 
  JOIN tblhosting h
    ON h.id = a.relid 
  JOIN tblproducts p
    ON p.id = h.packageid 
  JOIN tblclients c
    ON c.id = h.userid 
 WHERE affiliateid = $affiliateid 
 ORDER 
    BY clearingdate DESC;
    ");
$data = mysql_fetch_array($result);
$pendingcommissions = $data['?????????'];
$this->assign("pendingamount", $pendingcommissions);

我不确定的是在第三行输入?????????的内容。我已经尝试了所有这些东西,但没有一个有效:

$pendingcommissions = $data['SUM(tblaffiliatespending.amount)'];
$pendingcommissions = $data['SUM'];
$pendingcommissions = $data['tblaffiliatespending.amount'];
$pendingcommissions = $data['tblaffiliatespending'];
$pendingcommissions = $data['amount'];

关于需要改变什么的任何想法?

1 个答案:

答案 0 :(得分:0)

您需要为金额SUM(s.amount) total_amount的总和提供别名,因此当您执行查询并从中获取结果时,您将获得结果数组中total_amount索引上的金额列的总和你可以通过$data['total_amount'];访问它,同时注意使用聚合函数而不进行分组,然后将导致单行不是每组

SELECT SUM(s.amount) total_amount
  FROM tblaffiliatespending s
  JOIN tblaffiliatesaccounts a
    ON a.id=s.affaccid 
  JOIN tblhosting h
    ON h.id = a.relid 
  JOIN tblproducts p
    ON p.id = h.packageid 
  JOIN tblclients c
    ON c.id = h.userid 
 WHERE affiliateid = $affiliateid 
 ORDER 
    BY clearingdate DESC