2012-12-18 67 views
3

我正在使用mysql 5.1。SQL,COUNT在我的mysql查詢中不起作用

這裏是我的數據庫架構

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

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

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

我想算number of employeesgroup 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 

回答

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 
+0

嗨,employee_hierarchy.factory_id不存在,我已經更新我的數據庫架構,通過添加我的employee_hierarchy表。 –

+0

@ Tom-pouce看到我的更新。 –

+0

「字段列表」中的未知列'b.employee_hierarchy_description' –

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 

希望這有助於!