最近要进行性能优化,除了业务逻辑(要涉及代码重构),可以修改的就是SQL了,本次只是纯SQL层面的优化,不涉及数据库的层次,当然,索引还是要加的。
-
尽量减少多表关联(
join
),对 select 字段 使用 子查询的方式select t1.a,t2.c from table1 t1 left join table2 t2 on t1.id = t2.tid
可以改为:
select t1.a, (select t2.c from table2 t2 where t1.id = t2.tid) c from table1 t1
这样不但可以减少数据基量,还可以使用tid的索引。
-
减少多表关联(
join
),对主表的where条件使用in (子查询)
的方式select t1.a from table1 t1 left join table2 t2 on t1.id = t2.tid where t2.c = 123
可以改为:
select t1.a from table1 t1 where t1.id in ( select t2.tid from table2 t2 where t2.c = 123 )
-
where条件匹配时,注意等号两边类型要一致
比如where t1.id=t2.tid,t1.id是 varchar ,而t2.tid 是nvarchar;
或者where t1.id = ‘123’。 类型不一致也将导致索引失效。 -
避免对字段列使用函数,否则索引也会失效
-
添加合适的索引