MySQL:将两个表与空值组合在一起不会打印0

时间:2016-11-18 03:25:25

标签: mysql join datatable

在我的代码中,我尝试合并两个数据表EmployeeDepartment。我试着写一个查询来打印所有部门的相应部门名称和员工数量,甚至是无人值守的部门。我的查询如下:

SELECT department.name, count(department.name) AS CountOfNAME
FROM department LEFT JOIN employee ON department.dept_id = employee.dept_id
GROUP BY department.name
ORDER BY Count(department.name) DESC, department.name ASC;

结果是:

Engineering 5
Recruitment 5
Sales 3
Product 2
Finance 1
Operations 1
Research&Development 1

此代码的工作原理是它按员工数量排序部门,然后按字母顺序排序,但FinanceResearch&Development不应该包含任何人员。有没有办法正确显示这些结果为0员工?由于连接的工作原理,在SQL中做起来似乎很难。

2 个答案:

答案 0 :(得分:1)

COUNT函数应忽略NULL值,为金融和研究部门提供零计数。问题是,您正在计算department表中的列,该列始终为非NULL,因为此表位于LEFT JOIN的左侧。相反,请尝试计算employee表中的列:

SELECT department.name,
       COUNT(employee.dept_id) AS CountOfNAME
FROM department
LEFT JOIN employee
    ON department.dept_id = employee.dept_id
GROUP BY department.name
ORDER BY COUNT(employee.dept_id) DESC,
         department.name ASC;

答案 1 :(得分:0)

我建议您按部门创建员工姓名的视图,例如

  CREATE VIEW DepartmentEmployeeTallies
  AS
  SELECT dept_id, COUNT(*) AS tally
    FROM employee
  UNION
  SELECT dept_id, 0 AS tally
    FROM department
   WHERE dept_id NOT IN ( SELECT dept_id FROM employee );

然后事情就解决了简单的连接:

SELECT name, tally
  FROM department 
       NATURAL JOIN 
       DepartmentEmployeeTallies;