1、创建基表测试数据
1 | CREATE TABLE `test1` ( |
2、创建中间表
1 | CREATE TABLE `testfororder` ( |
创建存储过程对中间表插入数据:
1 | drop procedure if exists test; |
3、创建测试表:
1 | CREATE TABLE `sequence` ( |
数据量根据自己需求可以多次导入
4、查看sequence测试表数据:
1 | select count(*) from sequence; |
age条件筛选数据量
1 | select count(*) from sequence where age in (26,19,22,20,28,29,25); |
newid条件筛选数量
1 | select count(*) from sequence where newid in (116670,116677,116684,116691,116698,116705,116719,116726); |
5、where条件(age,newid)在没有创建索引的情况下:
age在前,newid在后,查看执行计划:
1 | explain select * from sequence where age in (26,19,22,20,28,29,25) and newid in (116670,116677,116684,116691,116698,116705,116719,116726); |
newid在前,age在后:
1 | explain select * from sequence where newid in (116670,116677,116684,116691,116698,116705,116719,116726) and age in (26,19,22,20,28,29,25); |
没有任何索引的情况下,where后面跟的条件从左到右,返回数据越小的条件在前面,效率会优于返回数据较大的条件在前面。
6、where条件(age)在没有创建索引,newid创建索引的情况下:
创建newid的索引:
1 | create index newid_ind on sequence(newid); |
age在前,newid在后:
1 | explain select * from sequence where age in (26,19,22,20,28,29,25) and newid in (116670,116677,116684,116691,116698,116705,116719,116726); |
newid在前,age在后:
1 | explain select * from sequence where newid in (116670,116677,116684,116691,116698,116705,116719,116726) and age in (26,19,22,20,28,29,25); |
在newid创建索引的情况下,where后面的查询条件前后顺序对查询效率影响不大。
7、where条件(newid)在没有创建索引,age创建索引的情况下:
删除newid的索引:
1 | drop index newid_ind on sequence; |
创建age的索引:
1 | create index age_ind on sequence(age); |
age在前,newid在后:
1 | explain select * from sequence where age in (26,19,22,20,28,29,25) and newid in (116670,116677,116684,116691,116698,116705,116719,116726); |
newid在前,age在后:
1 | explain select * from sequence where newid in (116670,116677,116684,116691,116698,116705,116719,116726) and age in (26,19,22,20,28,29,25); |
创建age索引之后,执行计划会默认使用索引执行,但是因为age的筛选出来的数据量比较大,使用索引也不是特别理想。
8、where条件(newid,age)创建联合索引的情况下:
删除age索引,创建newid,age的联合索引:
1 | drop index age_ind on sequence; |
age在前,newid在后:
1 | explain select * from sequence where age in (26,19,22,20,28,29,25) and newid in (116670,116677,116684,116691,116698,116705,116719,116726); |
newid在前,age在后:
1 | explain select * from sequence where newid in (116670,116677,116684,116691,116698,116705,116719,116726) and age in (26,19,22,20,28,29,25); |
联合索引存在的情况下,where后面的查询条件前后顺序对查询效率影响不大,但是创建了联合索引之后要注意查询条件问题,如果是以(newid,age)的顺序创建的联合索引,如果where查询条件后面有newid会使用联合索引,但是如果where查询条件后面之后age则不会引用联合索引:
1 | explain select * from sequence where newid in (116670,116677,116684,116691,116698,116705,116719,116726); |