1. 程式人生 > >MySQL 部門 員工數量查詢

MySQL 部門 員工數量查詢

員工表 user



部門表 department



1.查詢每個部門的員工數量;

SELECT department.`name`,COUNT(*) from `user` inner JOIN department ON department.id=`user`.depart_id GROUP BY depart_id;


2.查詢每個部門的員工數量並 按數量從高到低排序;

SELECT department.`name`,COUNT(*) from `user` inner JOIN department ON department.id=`user`.depart_id GROUP BY depart_id ORDER BY COUNT(*) desc;

3.查詢員工數大於1的部門名以及部門員工數;

SELECT t2.name,t1.count from (SELECT depart_id as did ,count(*) as count from user GROUP BY depart_id HAVING count(*)>1)t1,department t2 WHERE t1.did=t2.id;