子查询和连接之间的性能?

发布于 2024-12-05 17:43:46 字数 827 浏览 1 评论 0原文

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;

enter image description here

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;

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独自唱情﹋歌 2024-12-12 17:43:46

正如您在执行计划中看到的那样,联接显然更好。 :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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文