2015-10-15 60 views
0

在xyz_dept工作的员工数量,我想找回找出节数在“销售”部门在检索表“销售”为沿工作的员工:MySQL的:xyz_dept和使用嵌套查询

+-------+------------------+ 
| name | count(e.dept_id) | 
+-------+------------------+ 
| Sales |    3 | 
+-------+------------------+ 

我可以通过下面的查询写:

mysql> select d.name, count(e.dept_id) 
    -> from department d, employee e 
    -> where e.dept_id = d.department_id and d.name='sales'; 

但我被教导已经嵌套查询提高查询的效率。 所以我试图用嵌套查询重写相同。 但我只去这个:

mysql> select count(*) 
    -> from  employee 
    -> where dept_id = (select department_id 
    ->     from department 
    ->     where name='sales'); 
+----------+ 
| count(*) | 
+----------+ 
|  3 | 
+----------+ 

我试过很多的组合,但没有希望。我怎样才能获得下表使用嵌套查询

+-------+------------------+ 
| name | count(e.dept_id) | 
+-------+------------------+ 
| Sales |    3 | 
+-------+------------------+ 

谢谢。

回答

1

请尝试以下查询:

select d.name, count(e.dept_id) 
    from employee e 
    INNER JOIN (select name,department_id from department where name='sales') d 
      on d.department_id = e.dept_id; 
+0

谢谢你这么多:) –