sql调优

# 避免select *

# 一般查都要limit限制,limit也可以限制修改的条数,例如:limit 1 就是只能修改1条

# 合并结果集并去重
(select * from user where id=1);
union
(select * from user where id=2);

# 小表驱动大表,user是小表,用in
select * from order where uid in(
    select uid from user where is_delete=0
);
# exists写法,外小里大,用exists
select * from userwhere where is_delete=0 and exists (
    select 1 from user where order.uid=order.uid
);

# 大量数据的插入,每批500条以内
insert into order(id,code,uid) values(1,'AAA',1),(2,'BBB',1),(3,'CCC',1);

# 连接查询代替子查询
# 子查询,子查询会创建临时表和删除临时表
select * from order where uid in(
    select uid from user where is_delete=0
);
# 连接查询
select o.* from order o
inner join user u on(o.uid=u.uid)
where is_delete=0;

# 当left join时会以左边的表驱动右边的表,所以左边要小表
select o.id,o.code,u.name
from order o
left join user u on(o.uid=u.uid)
where is_delete=0;

# 单表索引尽量控制在5个以内,单个索引中的字段不超过5个

# 数值类型比字符快!

# 金额用decimal

# 分组耗时,所以我们可以先条件,后分组

# 索引优化
# 查看是否走了索引
explain select * from userr where uid=2;

你可能感兴趣的:(sql,数据库)