我有两张桌子 - departments
和employees
。我想从departments
中选择所有列,并在每个部门添加一个包含多个子部门和员工数量的列。
简化表格如下:
departments
:
id name parent_id
---------------------------------
1 IT NULL
2 HR NULL
3 Bussiness NULL
4 Web dev 1
5 Ecommerce 4
6 Advertisement 3
7 Control 3
8 Programmers 1
employees
:
id name department_id
---------------------------------
1 Adam 1
2 Ben 8
3 Charles 7
4 David 4
5 Eugen 4
6 Frank 6
7 Gustav 6
8 Heremy 4
9 Igor 5
10 Jacob 3
我想要的结果是:
id name parent_id department_count employee_count
----------------------------------------------------------------------------
1 IT NULL 2 1
2 HR NULL 0 0
3 Bussiness NULL 2 1
4 Web dev 1 1 3
5 Ecommerce 4 0 1
6 Advertisement 3 0 2
7 Control 3 0 1
8 Programmers 1 0 1
这是我的查询,但它无法正常工作。但是,如果我删除COUNT
中的1个,那么数字就是正确的。我认为NULL
值是问题,但我不知道解决方案。
SELECT d.*, COUNT(d2.parent_id) AS department_count, COUNT(e.id) AS employee_count
FROM department AS d
LEFT JOIN department AS d2 ON (d.id = d2.parent_id)
LEFT JOIN employees AS z ON (e.department_id = d.id)
GROUP BY d.id
ORDER BY d.id
欢迎对我的代码进行任何改进。
答案 0 :(得分:6)
在您的计数功能中使用d2.id
与不同,因此部门的重复子项将只计算一次
SELECT d.*,
COUNT(distinct d2.id) AS department_count,
COUNT(distinct e.id) AS employee_count
FROM department AS d
LEFT JOIN department AS d2 ON (d.id = d2.parent_id)
LEFT JOIN employees AS e ON (e.department_id = d.id)
GROUP BY d.id
ORDER BY d.id
答案 1 :(得分:4)
您可以尝试相关查询,因为它们提供了直接的逻辑:
SELECT d.*,
(SELECT COUNT(*) FROM departments WHERE parent_id = d.id) as department_count,
(SELECT COUNT(*) FROM employees WHERE department_id = d.id) as employees_count
FROM departments d