当前位置:网站首页>聊聊sql优化的15个小技巧
聊聊sql优化的15个小技巧
2022-07-25 19:02:00 【InfoQ】
前言

1 避免使用select *
select *select * from user where id=1;
select *覆盖索引回表select name,age from user where id=1;
2 用union all代替union
unionunion all(select * from user where id=1)
union
(select * from user where id=2);
(select * from user where id=1)
union all
(select * from user where id=2);
3 小表驱动大表
inselect * from order
where user_id in (select id from user where status=1)
existsselect * from order
where exists (select 1 from user where order.user_id = user.id and status=1)
子查询语句in适用于左边大表,右边小表。
exists适用于左边小表,右边大表。
4 批量操作
for(Order order: list){
orderMapper.insert(order):
}
insert into order(id,code,user_id)
values(123,'001',100);
orderMapper.insertBatch(list):
insert into order(id,code,user_id)
values(123,'001',100),(124,'002',100),(125,'003',101);
5 多用limit
select id, create_date
from order
where user_id=123
order by create_date asc;
List<Order> list = orderMapper.getOrderList();
Order order = list.get(0);
select id, create_date
from order
where user_id=123
order by create_date asc
limit 1;
limit 1update order set status=0,edit_time=now(3)
where id>=100 and id<200 limit 100;
6 in中值太多
inselect id,name from category
where id in (1,2,3...100000000);
select id,name from category
where id in (1,2,3...100)
limit 500;
public List<Category> getCategory(List<Long> ids) {
if(CollectionUtils.isEmpty(ids)) {
return null;
}
if(ids.size() > 500) {
throw new BusinessException("一次最多允许查询500条记录")
}
return mapper.getCategoryList(ids);
}
7 增量查询
select * from user;
select * from user
where id>#{lastId} and create_time >= #{lastCreateTime}
limit 100;
8 高效的分页
limitselect id,name,age
from user limit 10,20;
select id,name,age
from user limit 1000000,20;
select id,name,age
from user where id > 1000000 limit 20;
betweenselect id,name,age
from user where id between 1000000 and 1000020;
9 用连接查询代替子查询
子查询连接查询select * from order
where user_id in (select id from user where status=1)
inselect o.* from order o
inner join user u on o.user_id = u.id
where u.status=1
10 join的表不宜过多
3select a.name,b.name.c.name,d.name
from a
inner join b on a.id = b.a_id
inner join c on c.b_id = b.id
inner join d on d.c_id = c.id
inner join e on e.d_id = d.id
inner join f on f.e_id = e.id
inner join g on g.f_id = f.id
select a.name,b.name.c.name,a.d_name
from a
inner join b on a.id = b.a_id
inner join c on c.b_id = b.id
冗余专门的字段11 join时要注意
joinleft join:求两个表的交集外加左表剩下的数据。
inner join:求两个表交集的数据。
select o.id,o.code,u.name
from order o
inner join user u on o.user_id = u.id
where u.status=1;
select o.id,o.code,u.name
from order o
left join user u on o.user_id = u.id
where u.status=1;
12 控制索引的数量
5513 选择合理的字段类型
charalter table order
add column code char(20) NOT NULL;
varcharalter table order
add column code varchar(20) NOT NULL;
- 能用数字类型,就不用字符串,因为字符的处理往往比数字要慢。
- 尽可能使用小的类型,比如:用bit存布尔值,用tinyint存枚举值等。
- 长度固定的字符串字段,用char类型。
- 长度可变的字符串字段,用varchar类型。
- 金额字段用decimal,避免精度丢失问题。
14 提升group by的效率
group byhavingselect user_id,user_name from order
group by user_id
having user_id <= 200;
select user_id,user_name from order
where user_id <= 200
group by user_id
15 索引优化
索引优化explainexplain select * from `order` where code='002';



force index边栏推荐
- 基于FPGA的1080P 60Hz BT1120接口调试过程记录
- Software testing (mind mapping)
- Analysis of the internet jam in IM development? Network disconnection?
- Yarn 安装与使用教程[通俗易懂]
- SQL Server 2019 安装教程
- Go code checking tool
- Gan, why ".Length! == 3??
- 常用的开发软件下载地址
- 基础乐理之音程的度数
- Process communication (Systemv communication mode: shared memory, message queue, semaphore)
猜你喜欢

从目标检测到图像分割简要发展史

Analysis of the internet jam in IM development? Network disconnection?

Baklib: make excellent product instruction manual

Real estate enterprises have launched a "war of guarantee"
![[open source project] stm32c8t6 + ADC signal acquisition + OLED waveform display](/img/5f/413f1324a8346d7bc4a9490702eef4.png)
[open source project] stm32c8t6 + ADC signal acquisition + OLED waveform display

How to design product help center? The following points cannot be ignored

How to change the chords after the tune of the song is changed

modelsim和quartus联合仿真PLL FIFO等IP核

微软Azure和易观分析联合发布《企业级云原生平台驱动数字化转型》报告

阿里云技术专家郝晨栋:云上可观测能力——问题的发现与定位实践
随机推荐
The difference between QT exec and show
[encryption weekly] has the encryption market recovered? The cold winter has not thawed yet! Check the major events in the encryption market last week!
弱网测试工具-QNET
Qtimgui compilation
优秀的测试/开发程序员突破,不忘初心,方得始终......
Go代码检查工具
GDB help
F5: Six capabilities required for enterprise digital transformation
怎样设计产品帮助中心?以下几点不可忽视
srec_ Use of common cat parameters
Go code checking tool
The bank's wealth management subsidiary accumulates power to distribute a shares; The rectification of cash management financial products was accelerated
MySQL sub query (selected 20 sub query exercises)
JS 基本类型 引用类型 深/浅克隆复制
CircleIndicator组件,使指示器风格更加多样化
Pymoo学习 (6):终止条件
2022 Robocom 省赛题解
21 days proficient in typescript-4 - type inference and semantic check
srec_cat 常用参数的使用
[web technology] 1391 page visualization building tool, previous life and present life