sql 合并求和 3

sql join and sum 3

我对联接和求和列有疑问。我的查询是

SELECT 
sum(IFNULL(`worker_hours`.`godziny`, 0)) as godziny,
sum(IFNULL(`worker_hours`.`wartosc`, 0)) as wartosc,
sum(IFNULL(`worker_cashes`.`kwota`, 0)) as kwota,
`workers`.*
FROM 
`workers`
LEFT join `worker_hours` on `worker_hours`.`pracownik` = `workers`.`id`
LEFT join `worker_cashes` on `worker_cashes`.`pracownik` = `workers`.`id`
WHERE `workers`.`id_user` = '3'
group by
  `workers`.`id`

结果sum *2 我的查询,我做错了什么?我有这个查询没问题:

SELECT 
sum(IFNULL(`worker_hours`.`godziny`, 0)) as godziny,
sum(IFNULL(`worker_hours`.`wartosc`, 0)) as wartosc,
`workers`.*
FROM 
`workers`
left join `worker_hours` on `worker_hours`.`pracownik` = `workers`.`id`
WHERE `workers`.`id_user` = '3'
group by
  `workers`.`id`

问题是第二个left join

您应该首先在表 worker_hoursworker_cashes 中进行聚合,然后将 workers 连接到聚合的结果集,这样您就不会多次获得同一行到多个连接:

SELECT w.*,
       COALESCE(h.godziny, 0) AS godziny,
       COALESCE(h.wartosc, 0) AS wartosc,
       COALESCE(c.kwota, 0) AS kwota
FROM workers AS w
LEFT JOIN (
  SELECT pracownik,
         SUM(godziny) AS godziny,
         SUM(wartosc) AS wartosc
  FROM worker_hours 
  GROUP BY pracownik
) AS h ON h.pracownik = w.id
LEFT JOIN (
  SELECT pracownik,
         SUM(kwota) AS kwota
  FROM worker_cashes  
  GROUP BY pracownik
) AS c ON c.pracownik = w.id
WHERE w.id_user = '3';