问题介绍
创建数据库的索引,可以选择单列索引,也可以选择创建组合索引。
遇到如下这种情况,用户表(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)
对关联表的查询,有如下四种情况:
1 | -- 一、人员查所属部门用and方式 |
测试验证
一.人员查所属部门用and方式
1.1 关联表无索引

1.2 单索引 Idx_dept

1.3 单索引 Idx_user

1.4 组合索引 Idx_dept_user

1.5 组合索引 Idx_user_dept

1.6 所有都建立上

二 、人员查所属部门用join方式
2.1 关联表无索引

2.2 单索引 Idx_dept

2.3 单索引 Idx_user

2.4 组合索引 Idx_dept_user

2.5 组合索引 Idx_user_dept

2.6 所有都建立上

三 、部门查人员用and方式
3.1 关联表无索引

3.2 单索引 Idx_dept

3.3 单索引 Idx_user

3.4 组合索引 Idx_dept_user

3.5 组合索引 Idx_user_dept

3.6 所有都建立上

四 、部门查所属人员用join方式
4.1 关联表无索引

4.2 单索引 Idx_dept

4.3 单索引 Idx_user

4.4 组合索引 Idx_dept_user

4.5 组合索引 Idx_user_dept

4.6 所有都建立上

结论
通过上面的实际测试结果可以得出如下结论:针对于该关联表分别针对于user_uuid与dept_uuid建立单列索引idx_user,idx_dept最优。
其中索引idx_user适用与通过人员ID查询出该人员所在的部门;索引idx_dept适用与通过部门查询出该部门下所属的人员。
其它
测试数据
Test.sql相关资料
