如何进行查询以获得有区别的值?

bnl4lu3b  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(409)

我的应用程序有4个表:
员工->公司->附加->债务
我需要生成以下工资收据:
收据示例
在这个文件上,我必须显示所有歧视性的信息,如工资及其价值和费用。最后是额外资产和债务之间的净值。
我举了个例子:

$total_additional= 0;
$total_debt= 0;

// Here in employees contains a join between employees and companies
foreach ($employees as $employee) {

  foreach ($additionals as $additional) {
    if ( $employee->id == $additional->employee_id ) {
     //Print the additional reference
     $total_additional += $additional->value;
    }
  }

  foreach ($debts as $debt) {
    if ( $employee->id == $debt->employee_id ) {
     //Print the debt reference
     $total_debt += $debt->value;
    }
  }

  // Here should come the net value

}

如何进行查询以获取这些结果?

ncgqoxb0

ncgqoxb01#

用一些怎么样 LEFT JOIN 是的, GROUP BY 条款和 SUM 聚合以在一个查询中获得所有数据,而不必在php中循环?

SELECT employees.id, employees.name, 
    GROUP_CONCAT(additionals.value SEPARATOR '|') as additionals_values, SUM(additionals.value) as total_additional
FROM employees
LEFT JOIN additionals ON additionals.employee_id = employees.id
GROUP BY employees.id, employees.name;

SELECT employees.id, employees.name, 
    GROUP_CONCAT(debts.value SEPARATOR '|') as debts_values, SUM(debts.value) as total_debt
FROM employees
LEFT JOIN debts ON debts.employee_id = employees.id
GROUP BY employees.id, employees.name;

在php中使用 explode('|'... 具有单个值的数组。净值可以通过第三次查询或php计算。

相关问题