mysql join 组合索引_详解MySQL两表关联的连接表创建单列索引还是组合索引最优...
概述
今天主要介紹一下MySQL中兩表關(guān)聯(lián)的連接表是如何創(chuàng)建索引的相關(guān)內(nèi)容,下面來看看詳細(xì)的介紹。
MySQL兩表關(guān)聯(lián)的連接表創(chuàng)建索引
創(chuàng)建數(shù)據(jù)庫(kù)的索引,可以選擇單列索引,也可以選擇創(chuàng)建組合索引。
假設(shè)用戶表(user)與部門表(dept)通過部門用戶關(guān)聯(lián)表(deptuser)連接起來,如下圖所示:
表間關(guān)系
問題就是,在這個(gè)關(guān)聯(lián)表中該如何建立索引呢?
針對(duì)該表,有如下四種選擇:
針對(duì)于user_uuid建立單列索引idx_user
針對(duì)于user_dept建立單列索引idx_dept
建立組合索引idx_user_dept,即(user_uuid,dept_uuid)
建立組合索引idx_dept_user,即(dept_uuid,user_uuid)
對(duì)關(guān)聯(lián)表的查詢,有如下四種情況:
1、人員查所屬部門用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";
2、人員查所屬部門用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";
3、部門查人員用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";
4、部門查所屬人員用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";
01
人員查所屬部門用and方式
1.1 關(guān)聯(lián)表無索引
1.2 單索引 Idx_dept
1.3 單索引 Idx_user
1.4 組合索引 Idx_dept_user
1.5 組合索引 Idx_user_dept
1.6 所有都建立上
02
人員查所屬部門用join方式
2.1 關(guān)聯(lián)表無索引
2.2 單索引 Idx_dept
2.3 單索引 Idx_user
2.4 組合索引 Idx_dept_user
2.5 組合索引 Idx_user_dept
2.6 所有都建立上
03
部門查人員用and方式
3.1 關(guān)聯(lián)表無索引
3.2 單索引 Idx_dept
3.3 單索引 Idx_user
3.4 組合索引 Idx_dept_user
3.5 組合索引 Idx_user_dept
3.6 所有都建立上
04
部門查所屬人員用join方式
4.1 關(guān)聯(lián)表無索引
4.2 單索引 Idx_dept
4.3 單索引 Idx_user
4.4 組合索引 Idx_dept_user
4.5 組合索引 Idx_user_dept
4.6 所有都建立上
總結(jié)
通過上面的實(shí)際測(cè)試結(jié)果可以得出如下結(jié)論:針對(duì)于該關(guān)聯(lián)表分別針對(duì)于user_uuid與dept_uuid建立單列索引idx_user,idx_dept最優(yōu)。
其中索引idx_user適用與通過人員ID查詢出該人員所在的部門;索引idx_dept適用與通過部門查詢出該部門下所屬的人員。
總結(jié)
以上是生活随笔為你收集整理的mysql join 组合索引_详解MySQL两表关联的连接表创建单列索引还是组合索引最优...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多囊卵巢如何调理
- 下一篇: linux cmake编译源码,linu