SUM无法正常工作

时间:2011-01-10 06:29:06

标签: php mysql sum left-join

希望我能得到一个LEFT JOIN + SUM问题的手。

背景:我正在建立一个财务系统,并希望计算给定月份内所有发票的价值(空白月份=空)。我有两张桌子:

tsm_finance_calendar - 包含'月'。 tsm_finance_invoices - 包含每张发票的详细信息。

我的查询:

<?php
$query = "SELECT tsm_finance_calendar.month,
                 SUM(tsm_finance_invoices.totalBilled)
          FROM tsm_finance_calendar
          LEFT JOIN tsm_finance_invoices
              ON tsm_finance_calendar.month = tsm_finance_invoices.month
          GROUP BY tsm_finance_calendar.month
          ORDER BY 'id'"; 
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
echo $row['month']. " - $". $row['SUM(totalBilled'];
echo "<br />";
}
?>

输出在正确的轨道上(月 - $ 空白),但缺少总和的结果。

任何帮助都会得到一个巨大的高五:)

谢谢, RR

3 个答案:

答案 0 :(得分:4)

在查询中使用as关键字

$query = "SELECT tsm_finance_calendar.month, SUM(tsm_finance_invoices.totalBilled) as sum FROM tsm_finance_calendar LEFT JOIN tsm_finance_invoices ON tsm_finance_calendar.month = tsm_finance_invoices.month GROUP BY tsm_finance_calendar.month ORDER BY 'id'"; 
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
echo $row['month']. " - $". $row['sum'];
echo "<br />";
}

答案 1 :(得分:0)

$row["month"]-$row["SUM(totalBilled)"]

你忘了关闭paren ^

答案 2 :(得分:0)

你错过了'SUM(totalBilled'那里的右括号吗?

echo $row['month']. " - $". $row['SUM(totalBilled'];

如果tsm_finance_invoices的月份字段与tsm_finance_calendar.month的值相似,我想知道你为什么需要JOIN?