多列单个索引和联合索引的区别

博客介绍了利用Spring Boot构建200w数据记录的查询情况,展示了无索引和新增索引后的查询耗时。还阐述了联合索引本质,指出多列索引在多条件查询时的弊端,同时给出加索引的相关知识点,如字段应在where条件中、数据量少不加索引等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用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、联合索引比对每个列分别建索引更有优势,因为索引建立得越多就越占磁盘空间,在更新数据的时候速度会更慢。另外建立多列索引时,顺序也是需要注意的,应该将严格的索引放在前面,这样筛选的力度会更大,效率更高。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸葛子房_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值