SQL 优化

2019-04-13  本文已影响0人  西安法律咨询服务平台与程序员

首先从展示一段未优化前的代码:

select s.name, s.age, c.number from 
    (
        select name, age, c_id as num from tableA
        union all 
        select name, age, c_id as num from tableB
    ) s jion tableC c on s.c_id = c.id
where s.name = :name and s.age = :age

上面的SQL 首先关联表tableA 和tableB,然后join tableC,最后使用where 语句进行条件的限制。该SQL存在的问题是将tableA 与talbeB union all 之后再使用where 语句进行限制,这样增加了SQL 的查询时间。

优化后:

select s.name, s.age, c.number from 
(
    select name, age, c_id as num from tableA where name = :name and age = :age
    union all 
    select name, age, c_id as num from tableB where name = :name and age = :age
) s jion tableC c on s.c_id = c.id

将涉及子表的查询条件移动至子表中,可以查看优化前后的执行计划,便明确优化的效果。编写代码时,精力第一时间往往集中在实现业务功能,可以忽略了实现方式的优劣,所以需要在实现业务功能后,需要重新审视一次自己的代码,是否有更加好的实现方式。

上一篇 下一篇

猜你喜欢

热点阅读