3

我正在使用 mysql 5.1。

这是我的数据库架构

office
+--------------+----------------+
| office_id    | office_name    |
+--------------+----------------+

employee
+--------------+-----------------------+------------+
| employee_id  | employee_hierarchy_id | office_id  |
+--------------+-----------------------+------------+

employee_hierarchy
+-----------------------+-------------------------------+
| employee_hierarchy_id | employee_hierarchy_description|
+-----------------------+-------------------------------+

我想计算number of employees group by employee_hierarchy_id每个office_id

这是我列出 factory_id 和 employee_hierarchy_id 的请求:

SELECT office_id, employee_hierarchy_id
FROM office, employee_hierarchy
ORDER BY office_id ASC 

如果我尝试添加计数,它只显示一行:

SELECT office_id, employee_hierarchy_id, COUNT(*)
FROM office, employee_hierarchy
ORDER BY office_id ASC
4

2 回答 2

7

添加WHERE条件和GROUP BY从句

SELECT office_id, employee_hierarchy_id, COUNT(*)
FROM office, employee_hierarchy
WHERE office.factory_id = employee_hierarchy.factory_id
GROUP BY office_id, employee_hierarchy_id
ORDER BY office_id ASC

推荐的语法

SELECT office_id, employee_hierarchy_id, COUNT(*)
FROM office INNER JOIN employee_hierarchy
        ON office.factory_id = employee_hierarchy.factory_id
GROUP BY office_id, employee_hierarchy_id
ORDER BY office_id ASC

更新 1

如果您想在没有员工的情况下仍显示办公室记录,请使用LEFT JOIN,否则INNER JOIN

SELECT  a.office_name , c.employee_hierarchy_description,
        COUNT(b.office_ID) totalCount
FROM    office a
        LEFT JOIN employee b
            ON a.office_ID = b.office_ID
        LEFT JOIN employee_hierarchy c
            ON b.employee_hierarchy_id = c.employee_hierarchy_id
GROUP BY a.office_name , c.employee_hierarchy_description
ORDER BY totalCount DESC
于 2012-12-18T15:04:51.757 回答
2

我找到了另一种方法,试试这个子查询

SELECT SUM(number_of_employees) as 'number of employee per factory',factory_id
FROM (
SELECT COUNT(*) as 'number_of_employees',employee.factory_id
FROM factory,employee
WHERE factory.factory_id = employee.factory_id
GROUP BY employee.employee_hierarchy_id
) AS tmptbl 
GROUP BY tmptbl.factory_id

希望这可以帮助!

于 2012-12-18T15:39:22.970 回答