利用spring boot 构建了200w的数据记录
package com.example.demo.init;
import com.example.demo.dao.StudentDao;
import com.example.demo.model.StudentEbo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author duanxiaoqiu
* @Date 2019-06-17 20:12
**/
@Slf4j
@Order(value = 0)
@Component
public class initData implements CommandLineRunner {
@Autowired
private StudentDao studentDao;
@Override
public void run(String... args) throws Exception {
log.info("=======init=======");
long start = System.currentTimeMillis();
List<StudentEbo> studentEbos = new ArrayList<>();
int num = 0;
for (int i = 0; i < 2000000; i++) {
StudentEbo studentEbo = new StudentEbo();
studentEbo.setName("xq" + i);
studentEbo.setColor("color" + i);
studentEbo.setSize("size" + i);
studentEbos.add(studentEbo);
num++;
if (num == 10000) {
log.info("=======");
long time=System.currentTimeMillis();
studentDao.insertByBatch(studentEbos);
log.info("==time:{}===",System.currentTimeMillis()-time);
studentEbos.clear();
num = 0;
}
}
if (studentEbos != null && studentEbos.size() > 0) {
studentDao.insertByBatch(studentEbos);
}
log.info("======cost:{}======", System.currentTimeMillis() - start);
}
}
select * from t_student WHERE size='size10001'
耗时:0.747s
1.新增索引
ALTER TABLE `t_student` ADD INDEX `index1` (`size`) USING BTREE ;
查询耗时:0.248s
多列索引和联合索引参考:
https://www.cnblogs.com/musings/p/10890563.html
结论:
(1)联合索引本质:
当创建(a,b,c)联合索引时,相当于创建了(a)单列索引,(a,b)联合索引以及(a,b,c)联合索引
想要索引生效的话,只能使用 a和a,b和a,b,c三种组合;当然,我们上面测试过,a,c组合也可以,但实际上只用到了a的索引,c并没有用到!
注:这个可以结合上边的 通俗理解 来思考!
(2)多列索引:----不建议使用
多个单列索引在多条件查询时只会生效第一个索引!所以多条件联合查询时最好建联合索引!
(3)其他知识点:
1、需要加索引的字段,要在where条件中
2、数据量少的字段不需要加索引;因为建索引有一定开销,如果数据量小则没必要建索引(速度反而慢)
3、如果where条件中是OR关系,加索引不起作用
4、联合索引比对每个列分别建索引更有优势,因为索引建立得越多就越占磁盘空间,在更新数据的时候速度会更慢。另外建立多列索引时,顺序也是需要注意的,应该将严格的索引放在前面,这样筛选的力度会更大,效率更高。