多个左连接和SUM不正确添加

时间:2015-04-23 19:26:14

标签: php mysql sum

嘿所有我试图让SUM使用LEFT连接查询并且它根本不会添加值,即使我在WHILE语句中返回结果时它显示了要添加的正确值。

$lpcntWbqa = "SELECT portfolio_ledger.*,SUM(portfolio_ledger.plAmount) AS sum, portfolio_info.*,properties.*,property_portfolio.* 
FROM portfolio_ledger 
LEFT JOIN portfolio_info ON portfolio_ledger.psID = portfolio_info.ID 
LEFT JOIN property_portfolio ON portfolio_info.ppID = property_portfolio.ppID 
LEFT JOIN properties ON property_portfolio.pID = properties.pID 
WHERE properties.pOwner = '".$oRow['oID']."' 
AND portfolio_ledger.plNotify >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' ) 
AND portfolio_ledger.plNotify < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' ) 
AND (portfolio_ledger.plName = 'ST-Booking Fee' 
OR portfolio_ledger.plName = 'LT-Booking Fee') 
GROUP BY portfolio_ledger.psID"; 

在测试时我会返回结果。

// testing
 while ($alpTypeRow = mysql_fetch_array($lpcntXbqa))
 {
    echo "Booking: ".$alpTypeRow['plID']." - ".$alpTypeRow['plAmount']."<br />";
    $lastMonthsBookingValue = number_format($alpTypeRow['sum'], 2, '.', '');
 }
 echo $lastMonthsBookingValue;
// end testing

对于特定日期范围,回显结果为2行,这是正确的:值为1250和850,但$ lastMonthsBookingValue仅返回850.不是一起添加的项目。

任何建议或协助将不胜感激。我一直在研究网络,也许我需要做一个嵌套的SELECT但不确定如何做到这一点。

1 个答案:

答案 0 :(得分:0)

我终于有了这个工作。它似乎是GROUP BY方面,以及我表中的一些不规则数据用于记录。一些日期;是我怀疑的。感谢您的评论和建议。

$lpcntWbqa = "SELECT portfolio_ledger.*,SUM(portfolio_ledger.plAmount) AS sum, portfolio_info.*,properties.*,property_portfolio.* FROM portfolio_ledger LEFT JOIN portfolio_info ON portfolio_ledger.psID = portfolio_info.ID LEFT JOIN property_portfolio ON portfolio_info.ppID = property_portfolio.ppID LEFT JOIN properties ON property_portfolio.pID = properties.pID WHERE properties.pOwner = '".$oRow['oID']."' AND portfolio_ledger.plNotify >= DATE_FORMAT( CURRENT_DATE - INTERVAL 1 MONTH, '%Y/%m/01' ) AND portfolio_ledger.plNotify < DATE_FORMAT( CURRENT_DATE, '%Y/%m/01' ) AND (portfolio_ledger.plName = 'ST-Booking Fee' OR portfolio_ledger.plName = 'LT-Booking Fee')";

并像以前一样返回值;一切都很好地计算和SUMS。

while($ lpTypeRow = mysql_fetch_array($ lpcntXbqa)) {

$lastMonthsBookingValue = number_format($lpTypeRow['sum'], 2, '.', '');

}

再次感谢!祝你好运!