问题介绍
创建数据库的索引,可以选择单列索引,也可以选择创建组合索引。
遇到如下这种情况,用户表(user)与部门表(dept)通过部门用户关联表(deptuser)连接起来,如下图所示:针对该表,有如下四种选择:
针对于user_uuid建立单列索引idx_user
针对于user_dept建立单列索引idx_dept
建立组合索引idx_user_dept,即(user_uuid,dept_uuid)
建立组合索引idx_dept_user,即(dept_uuid,user_uuid)
对关联表的查询,有如下四种情况:
-- 一、人员查所属部门用and方式
EXPLAIN SELECT d.dept_name,u.* FROM org_dept d,org_user u,org_dept_user duser WHERE u.user_uuid=duser.user_uuid AND d.dept_uuid=duser.dept_uuid AND u.user_code="dev1";
-- 二、人员查所属部门用join方式
EXPLAIN SELECT d.dept_name,u.* FROM org_user u LEFT JOIN org_dept_user du ON u.user_uuid=du.user_uuid LEFT JOIN org_dept d ON du.dept_uuid=d.dept_uuid WHERE u.user_code="dev1";
-- 三、部门查人员用and方式
EXPLAIN SELECT d.dept_name,u.* FROM org_dept d,org_user u,org_dept_user du WHERE u.user_uuid=du.user_uuid AND d.dept_uuid=du.dept_uuid AND d.dept_code="D006";
-- 四、部门查所属人员用join方式
EXPLAIN SELECT d.dept_name,u.* FROM org_dept d LEFT JOIN org_dept_user du ON d.dept_uuid=du.dept_uuid LEFT JOIN org_user u ON u.user_uuid=du.user_uuid WHERE d.dept_code="D006";
测试验证
一.人员查所属部门用and方式
1.1 关联表无索引1.2 单索引 Idx_dept
1-2.png1.3 单索引 Idx_user
1-3.png1.4 组合索引 Idx_dept_user
1-4.png1.5 组合索引 Idx_user_dept
1-5.png1.6 所有都建立上
1-6.png二 、人员查所属部门用join方式
2.1 关联表无索引
2-1.png2.2 单索引 Idx_dept
2-2.png2.3 单索引 Idx_user
2-3.png2.4 组合索引 Idx_dept_user
2-4.png2.5 组合索引 Idx_user_dept
2-5.png2.6 所有都建立上
2-6.png三 、部门查人员用and方式
3.1 关联表无索引
3-1.png3.2 单索引 Idx_dept
3-2.png3.3 单索引 Idx_user
3-3.png3.4 组合索引 Idx_dept_user
3-4.png3.5 组合索引 Idx_user_dept
3-5.png3.6 所有都建立上
3-6.png四 、部门查所属人员用join方式
4.1 关联表无索引
4-1.png4.2 单索引 Idx_dept
4-2.png4.3 单索引 Idx_user
4-3.png4.4 组合索引 Idx_dept_user
4-4.png4.5 组合索引 Idx_user_dept
4-5.png4.6 所有都建立上
4-6.png
结论
通过上面的实际测试结果可以得出如下结论:针对于该关联表分别针对于user_uuid与dept_uuid建立单列索引idx_user,idx_dept最优。
其中索引idx_user适用与通过人员ID查询出该人员所在的部门;索引idx_dept适用与通过部门查询出该部门下所属的人员。
其它
测试数据
相关资料