2011-09-20 22 views
0
Both queries generates a list of department IDs along with the number 
of employees assigned to each department. 

我能夠獲得兩種以上使用聯接和子查詢的結果,但我非常渴望知道 兩個查詢是如何工作的performance這是更好的條款:加入或子查詢。 我已經爲這兩個查詢添加了解釋計劃屏幕截圖,但我不明白它的含義。子查詢和連接之間的性能?

使用加入

SELECT d.dept_id, d.name, count(emp_id) AS num_employee 
FROM department d INNER JOIN employee e ON e.dept_id = d.dept_id 
GROUP BY dept_id; 

enter image description here

使用子查詢

SELECT d.dept_id, d.name, e_cnt.how_many num_employees 
FROM department d INNER JOIN 
(SELECT dept_id, COUNT(*) how_many 
FROM employee 
GROUP BY dept_id) e_cnt 
ON d.dept_id = e_cnt.dept_id; 

enter image description here

+0

具有u測試性能? – rabudde

+0

作爲一個經驗法則 - 聯接幾乎總是在性能方面更好 – Galz

+0

又見http://dev.mysql.com/doc/refman/5.1/en/explain-output.html(爲'type'的解釋欄) – rabudde

回答

4

在你的執行計劃中,連接顯然更好。 :P

子選擇正在使用索引來獲取初始表(count(*),dept_id),然後使用緩衝表連接到外部select語句以獲得結果。

內連接使用兩個部門和員工的指標來確定匹配行拯救自己的緩存表的創建和初始索引查找。

+0

我沒有得到執行計劃能否詳細解釋它? –

+0

@ViswanathanIyer看到我的更新。 – Icarus