获取mysql JOIN查询后的列行总和

时间:2012-10-31 19:11:36

标签: php mysql sql

$r1 = mysql_query("
SELECT *, SUM(bps.price) as sum FROM accounts 
FULL JOIN bps on bps.id = mid
");
echo "Total price: ".$row['price']."<br>" ;
    while($row = mysql_fetch_array($r1))
      {
      echo $row['name']." <b>:::</b>  ".$row['mid']." <b>:::</b>  ".$row['price'];
      echo "<br />";
      }

这是我的查询。我需要得到列的总和(总和):bps.price 一些行有:10.5,其他-5.5等...换句话说,有些是负值,有些是正数。它会列出所有结果,然后在最后显示列价的总和。

2 个答案:

答案 0 :(得分:1)

select sum(bps.price) FROM accounts a
FULL JOIN bps on bps.id = a.mid

那会有效,对吗?它将总和正值和负值相加,这无关紧要。

答案 1 :(得分:1)

这是否按您想要的方式工作?我不确定哪些列属于哪些表,只需根据需要编辑表名(a / b)......

$r1 = mysql_query("
SELECT *, sum(a.price) as sum FROM accounts as a 
FULL JOIN bps as b on a.mid = b.id
");
echo "Total price: ".$row['sum']."<br>" ;
    while($row = mysql_fetch_array($r1))
      {
      echo $row['a.name']." <b>:::</b>  ".$row['a.mid']." <b>:::</b>  ".$row['a.price'];
      echo "<br />";
      }