MySQL两表联查创建索引

来源:互联网 发布:php indexof 编辑:程序博客网 时间:2024/06/06 14:26

创建数据库的索引,可以选择单列索引,也可以选择创建组合索引。

  遇到如下这种情况,用户表(user)与部门表(dept)通过部门用户关联表(deptuser)连接起来,如下图所示:

表间关系

表间关系

  问题就是,在这个关联表中该如何建立索引呢?

针对该表,有如下四种选择:

  1. 针对于user_uuid建立单列索引idx_user
  2. 针对于user_dept建立单列索引idx_dept
  3. 建立组合索引idx_user_dept,即(user_uuid,dept_uuid)
  4. 建立组合索引idx_dept_user,即(dept_uuid,user_uuid)

对关联表的查询,有如下四种情况:

1
2
3
4
5
6
7
8
9
10
11
-- 一、人员查所属部门用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-1.png

1.2 单索引 Idx_dept

1-2.png

1.3 单索引 Idx_user

1-3.png

1.4 组合索引 Idx_dept_user

1-4.png

1.5 组合索引 Idx_user_dept

1-5.png

1.6 所有都建立上

1-6.png

二 、人员查所属部门用join方式

2.1 关联表无索引

2-1.png

2.2 单索引 Idx_dept

2-2.png

2.3 单索引 Idx_user

2-3.png

2.4 组合索引 Idx_dept_user

2-4.png

2.5 组合索引 Idx_user_dept

2-5.png

2.6 所有都建立上

2-6.png

三 、部门查人员用and方式

3.1 关联表无索引

3-1.png

3.2 单索引 Idx_dept

3-2.png

3.3 单索引 Idx_user

3-3.png

3.4 组合索引 Idx_dept_user

3-4.png

3.5 组合索引 Idx_user_dept

3-5.png

3.6 所有都建立上

3-6.png

四 、部门查所属人员用join方式

4.1 关联表无索引

4-1.png

4.2 单索引 Idx_dept

4-2.png

4.3 单索引 Idx_user

4-3.png

4.4 组合索引 Idx_dept_user

4-4.png

4.5 组合索引 Idx_user_dept

4-5.png

4.6 所有都建立上

4-6.png

结论

  通过上面的实际测试结果可以得出如下结论:针对于该关联表分别针对于user_uuid与dept_uuid建立单列索引idx_user,idx_dept最优。

  其中索引idx_user适用与通过人员ID查询出该人员所在的部门;索引idx_dept适用与通过部门查询出该部门下所属的人员。

原文路径:http://blog.csdn.net/yzf913214/article/details/72232187

原创粉丝点击