我有 3 个表 ,table salaries(id, name) and pointages(id, datep, salarie_id, sold) and avances(id,montantA, salarie_id).
tables salaries
Id name
1 kamal
2 imad
pointages table
id datep Salarie_id sold
1 11/03/2020 1 120
2 05/03/2020 1 100
3 06/03/2020 2 50
4 07/03/2020 2 20
avances table
id datea montantA Salarie_id
1 11/03/2020 120 1
2 02/03/2020 50 1
通过这 3 个表,我想像这样恢复salary.id 和salary.name 和 sum (pointages.sold) 和 sum (avances.montantA)
Salarie.id Salaries.name Sum(sold) Sum(montantA)
1 kamal 220 170
2 imad 70 0
当我执行 mysql 请求时,它给了我一个确切的结果:
SELECT
s.id AS 'Salarie.id',
s.nom AS 'Salarie.nom',
COALESCE(p.somme, 0) AS 'SUM(sold)',
COALESCE(a.somme, 0) AS 'SUM(montantA)'
FROM Salaries s
LEFT JOIN (SELECT SUM(sold) AS somme, salarie_id FROM pointages
GROUP BY salarie_id) AS p ON p.salarie_id = s.id
LEFT JOIN (SELECT SUM(montantA) AS somme, salarie_id FROM avances
GROUP BY salarie_id) AS a ON a.salarie_id = s.id
GROUP BY s.id, p.salarie_id, a.salarie_id
现在我想在 SalarieController 的状态函数中编写此查询,但我不知道如何
如果像下面这样使用 sum结果就是几位的值,就不对了
SELECT
s.id AS 'Salarie.id',
s.nom AS 'Salarie.nom',
COALESCE(p.somme, 0) AS 'SUM(sold)',
COALESCE(a.somme, 0) AS 'SUM(montantA)'
FROM
Salaries s
LEFT JOIN pointages AS p ON p.salarie_id = s.id
LEFT JOIN avances ON a.salarie_id = s.id
GROUP BY s.id, p.salarie_id, a.salarie_id