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

标签 mysql sql performance join subquery

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

最佳答案

如您在执行计划中所见,连接明显更好。 :P

子选择使用索引获取初始表 (count (*), dept_id),然后使用缓冲表连接到外部选择语句以获得结果。

内连接使用部门和员工的索引来确定匹配的行,从而节省您创建缓冲表和初始索引查找的时间。

关于mysql - 子查询和连接之间的性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7490569/

相关文章:

performance - Hibernate 适合批处理吗?内存使用情况如何?

mysql - MongoDB 的论坛模型

mysql - 是否不需要创建额外的索引?

sql - SQL Server 2012 中基于列的查询加速器

c# - sql 在一个字符串匹配上连接两个表

sql - 在应用程序的数据库存储过程中使用 MSDB 存储过程

c++ - OCaml 中的快速位数组

c++ - 托管 C++ 与非托管/ native C++ 的性能对比

php - 密码不区分大小写

PHP 文件 - 导出 xls 而不是 csv