【问题标题】:MySQL: Combining two tables with null values does not print 0MySQL:将两个表与空值组合不打印 0
【发布时间】:2017-04-01 19:40:19
【问题描述】:

在我的代码中,我试图合并两个数据表,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 名员工?由于 join 的工作方式,在 SQL 中似乎很难做到。

【问题讨论】:

    标签: mysql join datatable


    【解决方案1】:

    COUNT 函数应忽略 NULL 值,为财务和研究部门提供零计数。问题是您正在计算department 表中的一列,由于该表位于LEFT JOIN 的左侧,因此该列总是非NULL。相反,请尝试计算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;
    

    【讨论】:

    • 这对于使 0 出现效果很好,但是发生了一些奇怪的事情。结果现在看起来像 Engineering 5 Recruitment 5 Sales 3 Product 2 Finance 0 Operations 1 Research&Development 0 ,其中 1 在某种程度上介于 0 之间,即使它是按部门名称的计数排序的。代码中是否存在导致此异常的内容?抱歉没看懂,我刚学SQL :)
    • 使用ORDER BY COUNT(employee.dept_id) DESC ...对不起
    • 非常感谢!
    【解决方案2】:

    我建议您按部门创建员工统计视图,例如

      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;
    

    【讨论】:

      猜你喜欢
      • 2017-03-04
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      相关资源
      最近更新 更多