子查询和连接之间的性能?
Both queries generates a list of department IDs along with the number
of employees assigned to each department.
我可以使用联接和子查询获得上述结果,但我非常想知道 就性能
而言,这两个查询如何工作:联接或子查询哪个更好。 我已经为这两个查询添加了解释计划屏幕截图,但我不明白它的含义。
使用 Join
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;
使用子查询
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;
Both queries generates a list of department IDs along with the number
of employees assigned to each department.
I'm able to get results for above both using joins and subquery but I'm very keen to know
how both queries works in terms of performance
which is better: joins or subquery.
I've added Explain Plan screen shot for both queries, but I don't understand what it means.
Using Join
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;
Using Subquery
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您在执行计划中看到的那样,联接显然更好。 :P
子查询使用索引来获取初始表(count (*), dept_id),然后使用缓冲表连接到外部 select 语句以获得结果。
内部联接使用部门和员工的索引来确定匹配的行,从而节省了缓冲表的创建和初始索引查找的时间。
The join is clearly better as you can see in your execution plan. :P
The subselect is using an index to get the initial table (count (*), dept_id) and then is using a buffer table to join to the outer select statement to get you your result.
The inner join uses the index on both department and employee to determine the matching rows saving yourself the creation of the buffer table and the initial index seek.