我正在使用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
答案 0 :(得分:7)
添加WHERE
consition和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
答案 1 :(得分: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
希望这有帮助!