当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL数据库小表驱动大表的优化教程

MySQL数据库小表驱动大表的优化教程

2018年10月25日  | 移动技术网IT编程  | 我要评论

优化原则:小表驱动大表,即小的数据集驱动大的数据集。

先来了解两个关键字:in和exists。建立两个表,员工表和部门表。分别用两个关键字来查询,一般员工表为大数据集,部门表为小数据集。

in:

select * 
from t_emp 
where dept_id in (select dept_id from t_dept) 
limit 5;

相当于:

for select dept_id from t_dept
    for select * from t_emp where t_emp.dept_id = t_dept.dept_id

先子查询,后主查询,即先查询部门,然后查询部门下的员工,即小表驱动大表。

exists:

select * 
 from t_emp 
 where exists 
     (select 1 
     from t_dept 
     where t_dept.dept_id = t_emp.dept_id);

相当于:

for select * from t_emp 
    for select * from t_dept  where t_dept.dept_id = t_emp.dept_id

先查员工表,再根据部门id查部门中是否存在,返回true or false,再决定员工表数据是去是留。大表驱动小表,查询效率较低。

扩展:

两个关键字可以反过来用,t_emp大于t_dept时,用in;小于时用exists。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网