左联接不获取所有记录

时间:2020-08-06 12:46:31

标签: sql left-join

我试图通过使用左联接获取结果从表中获取所有记录(组,雀巢,客户,目标,派别),如果用户ID不存在,则获取0(例如:未将目标分配给膜) 我不知道我是否能有效解释,但这是我的查询:

select CONCAT(s.firstname, ' ', s.lastname) AS Membre, g.achievement AS Objectif, count(l.assigned) AS `num_l`, count(c.id_fiche) AS `num_c`,
(count(c.id_fiche)/count(l.assigned))*100 AS `perc`, SUM(f.total) AS `glob`, (g.achievement - SUM(f.total)) AS `rest`, (SUM(f.total)/g.achievement)*100 AS `taux` 
from `groups` s 
LEFT JOIN `fiches` l ON s.id_membre=l.assigned LEFT JOIN `clients` c ON l.id=c.id_fiche 
LEFT JOIN `goals` g ON s.id_membre=g.id_membre LEFT JOIN `factures` f ON s.id_membre=f.addedfrom 
WHERE l.dateassigned BETWEEN  '2020-08-01' AND '2020-08-31' AND f.status=2 
GROUP BY s.id_membre

我得到的结果是为其分配了目标的成员,但是我需要的是所有成员,而没有为其分配目标的成员在与目标相关的字段中得到0。 谢谢。

3 个答案:

答案 0 :(得分:0)

LEFT JOIN很好。您已选择通过添加INNER JOIN子句将其变成WHERE

使用LEFT JOIN时,除第一个表外的所有过滤条件 应该处于ON条件中。

select CONCAT(s.firstname, ' ', s.lastname) AS Membre, g.achievement AS Objectif, 
       count(l.assigned) AS `num_l`, count(c.id_fiche) AS `num_c`, 
       (count(c.id_fiche)/count(l.assigned))*100 AS `perc`, SUM(f.total) AS `glob`, (g.achievement - SUM(f.total)) AS `rest`,
      (SUM(f.total)/g.achievement)*100 AS `taux`
from `groups` s LEFT JOIN
     `fiches` l
     ON s.id_membre = l.assigned AND
        l.dateassigned BETWEEN '2020-08-01' AND '2020-08-31' LEFT JOIN
     `clients` c
     ON l.id = c.id_fiche LEFT JOIN
     `goals` g
     ON s.id_membre = g.id_membre LEFT JOIN
     `factures` f
     ON s.id_membre = f.addedfrom AND f.status=2
GROUP BY s.id_membre

答案 1 :(得分:0)

您需要更改查询范围-

select CONCAT(s.firstname, ' ', s.lastname) AS Membre,
       g.achievement AS Objectif,
       count(l.assigned) AS `num_l`,
       count(c.id_fiche) AS `num_c`,
       (count(c.id_fiche)/count(l.assigned))*100 AS `perc`,
       SUM(f.total) AS `glob`,
       (g.achievement - SUM(f.total)) AS `rest`,
       (SUM(f.total)/g.achievement)*100 AS `taux`
  from `groups` s
  LEFT JOIN `fiches` l ON s.id_membre=l.assigned
                       AND l.dateassigned BETWEEN  '2020-08-01' AND '2020-08-31'
  LEFT JOIN `clients` c ON l.id=c.id_fiche
  LEFT JOIN `goals` g ON s.id_membre=g.id_membre
  LEFT JOIN `factures` f ON s.id_membre=f.addedfrom
                         AND f.status=2
 GROUP BY s.id_membre

答案 2 :(得分:0)

您只在运行左联接,因此不知道所有表,我的第一个直觉是在“ groups”表(所选的第一个表)中缺少成员本身。或者,尝试删除WHERE和AND条件,然后查看丢失的用户是否回来。