记一次MySQL 多表联查时多个left join优化

从以前的30s左右到优化后的0.07s,速度嗖嗖的,原sql及具体优化如下:

-- 方法一:
SELECT s.id ,s.title
        FROM school s
        LEFT JOIN area_school_link asl ON s.id = asl.school_id
        LEFT JOIN sys_area t1 ON asl.area_id = t1.id
        LEFT JOIN sys_area t2 ON t1.parent_id = t2.id
        WHERE s.deleted = 0 and (t2.id = 27 or t1.id = 27)

-- 原先代码 执行31s

SELECT s.id ,s.title
        FROM school s INNER JOIN (SELECT a.area_id,a.school_id FROM area_school_link a) b ON s.id = b.school_id 
        LEFT JOIN sys_area t1 ON b.area_id = t1.id
        LEFT JOIN sys_area t2 ON t1.parent_id = t2.id
        WHERE s.deleted = 0 and (t2.id = 27 or t1.id = 27)

-- 优化后代码 执行0.07s


-- 方法二:

-- 创建索引
create unique index index_id on school(id);

-- 删除索引
drop index index_id on school;

你可能感兴趣的:(java)