【发布时间】:2015-04-04 10:56:25
【问题描述】:
我正在尝试在 sql 查询中使用 Left Join 显示来自 3 个表的总和的表(带有数据表插件)信息。 我使用以下查询成功地编辑了服务器端查询并显示了两个表之间的第一个关节(t1=...budget & t2=..budget_changes)的正确数据:
$year=date('Y');
$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns)).",
IFNULL(SUM(t2.change_amount),0) AS operation_changes,
(t1.operation_BP+IFNULL(SUM(t2.change_amount),0)) AS operation_total
FROM budget AS t1
LEFT JOIN wp_dri_budget_changes AS t2 ON t2.change_year_operation=t1.operation_year_number
WHERE t1.operation_year=".$year." AND t1.operation_active=1 $sWhere
GROUP BY operation_year_number, change_year_operation $sOrder $sLimit";
但是当我尝试使用左联合查询连接 3 个表时,总和结果是错误的。
$year=date('Y');
$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns)).",
IFNULL(SUM(t2.change_amount),0) AS operation_changes,
(t1.operation_BP+IFNULL(SUM(t2.change_amount),0)) AS operation_total,
IFNULL(SUM(t3.expense_enga_amount),0) AS operation_consommation
FROM budget AS t1
LEFT JOIN wp_dri_budget_changes AS t2 ON t2.change_year_operation=t1.operation_year_number
LEFT JOIN wp_dri_budget_expenses AS t3 ON t3.expense_year_operation=t1.operation_year_number
WHERE t1.operation_year=".$year." AND t1.operation_active=1 $sWhere GROUP BY operation_year_number, change_year_operation, expense_year_operation $sOrder $sLimit";
这个查询有什么问题?非常感谢 MT
【问题讨论】:
-
发布一些输入数据和预期结果。
-
向我们展示表格结构
-
请合理格式化代码。请在代码问题中给出minimal reproducible example--cut & paste & runnable code,包括最小的代表性示例输入为代码;期望和实际输出(包括逐字错误消息);标签和版本;明确的规范和解释。给出您可以给出的最少代码,即您显示的代码可以通过您显示的代码扩展为不正常。 (调试基础。)对于包含 DBMS 和 DDL(包括约束和索引)和输入为格式化为表的代码的 SQL。 How to Ask
标签: php mysql sql sum left-join