簡單改寫SQL達到優化目的


select *
from (select t.row_id,
t.supplier_name,
t.tel,
address,
t.contact,
t.contact_post,
t.contact_mobi,
t.contact_tel,
case
when project_supp_type = 0 then
to_number(nvl(t.discount_rate, 0))
when project_supp_type2 = 0 then
to_number(nvl(t.discount_rate2, 0))
when project_supp_type3 = 0 then
to_number(nvl(t.discount_rate3, 0))
when project_supp_type4 = 0 then
to_number(nvl(t.discount_rate4, 0))
when project_supp_type5 = 0 then
to_number(nvl(t.discount_rate5, 0))
when project_supp_type6 = 0 then
to_number(nvl(t.discount_rate6, 0))
end as rate
from md_supplier t
where t.supplier_type = 4
and (project_supp_type = 0 or project_supp_type2 = 0 or
project_supp_type3 = 0 or project_supp_type4 = 0 or
project_supp_type5 = 0 or project_supp_type6 = 0)
and t.status = 1
and exists (select *
from md_project mp, md_project_supplier mps
where mp.row_id = mps.project_id
and mp.status = 1

and supplier_id = t.row_id)
order by rate desc, t.supplier_name)
where rownum <= 5
View Code

 

 這是原始sql,sql運行4秒出結果,網友反映比較慢

看了執行計划

執行計划沒有問題,驅動表全表掃描也只是返回27條,無傷大雅,被驅動表view VW_SQ_1

被驅動表內走了 merge jion,merge jion比nl要強一下,進行全表掃描之后再排序,之后再連接

問題要看exists中的表 返回227行,在view中 exists中的表有相當於一個驅動表了,他要驅動id 10,每次查詢都要全表 ,還要227次,就慢了,就需要改寫

將它提取出來,不讓他掃描多次,這就是思路

改寫之后的sql

with ttt as (select *
                    from md_project mp, md_project_supplier mps
                   where mp.row_id = mps.project_id
                     and mp.status = 1                     
)
select *
    from (select t.row_id,
                 t.supplier_name,
                 t.tel,
                 address,
                 t.contact,
                 t.contact_post,
                 t.contact_mobi,
                 t.contact_tel,
                 case
                   when project_supp_type = 0 then
                    to_number(nvl(t.discount_rate, 0))
                   when project_supp_type2 = 0 then
                    to_number(nvl(t.discount_rate2, 0))
                   when project_supp_type3 = 0 then
                    to_number(nvl(t.discount_rate3, 0))
                   when project_supp_type4 = 0 then
                    to_number(nvl(t.discount_rate4, 0))
                   when project_supp_type5 = 0 then
                    to_number(nvl(t.discount_rate5, 0))
                   when project_supp_type6 = 0 then
                    to_number(nvl(t.discount_rate6, 0))
                 end as rate
            from md_supplier t
           where t.supplier_type = 4
             and (project_supp_type = 0 or project_supp_type2 = 0 or
                 project_supp_type3 = 0 or project_supp_type4 = 0 or
                 project_supp_type5 = 0 or project_supp_type6 = 0)
             and t.status = 1
             and exists (select * from ttt where supplier_id = t.row_id)
           order by rate desc, t.supplier_name)
   where rownum <= 5
View Code

 

sql運行時間為0.03秒

 


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com