• 主次表关联,明细表的关联字段需要添加索引吗?
  • 发布于 2个月前
  • 286 热度
    0 评论
如下有两张表,批次表和明细表,明细表的batch_id关联批次表的主键id,所含字段均为涂鸦。
主表:desc t_batch

明细表:desc t_detail

下面造一些测试数据,考虑本地mysql是docker,数据量只造100w级,演示足矣。
--堆代码 duidaima.com
--基础数据
insert into t_batch(total, area, create_date)
select ceiling(rand() * 900000 + 1000000), case when rand() > 0.5 then '北京' else '上海' end, sysdate();
--批量造数
insert into t_batch(total, area, create_date) select total, area, create_date from t_batch;
--总数:
select count(id) from t_batch;

下面是明细表造数,简单贴下造数过程,不再赘述:
--堆代码 duidaima.com
insert into t_detail(batch_id, name, update_date) select 1,concat('star',round(rand()*10)),now();
update t_detail set batch_id = id;
insert into t_detail(batch_id, name, update_date) select batch_id,concat('star',round(rand()*10)),now() from t_detail;
验证,明细表关联查询批次表,主要是把批次表的关联信息带出来,关联查询两个表:
explain select t1.*,t2.area,t2.total from t_detail t1,t_batch t2 where t2.id=t1.batch_id;

显然明细表的查询是全表扫描,关联批次表走的是主键,根本不需要在明细表的batch_id上创建索引,即便创建了,也没个鸟用:

如果想不明白,不妨换个写法:
select t1.*,(select t2.area from t_batch t2 where t2.id = t1.batch_id ) from t_detail t1;
so,索引不是越多越好,更不是想当然的创建。
用户评论