最近要進行性能優化,除了業務邏輯(要涉及代碼重構),可以修改的就是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的索引,這裏有一點要注意,如果t1.id 和 t2.tid 兩個字段類型不一 致的話,索引將失效,比如t1.id 是 varchar ,而t2.tid 是nvarchar。
-
減少多表關聯(
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 )