2015-10-15 64 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

謝謝你這麼多:) –