2017-04-11 75 views
0

我正在嘗試改進下面查詢的速度,但所需字段無法更改。所以我被困在這裏。請幫我擺脫這個陷阱。一點提示或靈感也是有幫助的!嘗試優化PL/SQL查詢

select cg.province_id, 
    (select count(distinct(c.guidance_user_id)) 
     from case_guidance c 
    where c.guidance_status = '2' 
     and c.province_id = cg.province_id) as guidance_cnt, 
    (select count(distinct(c.guidance_user_id)) 
     from case_guidance c 
    where c.guidance_status = '2' 
     and c.guidance_user_type = 'role.type.teacher' 
     and c.province_id = cg.province_id) as guidance_teacher_cnt, 
    (select count(distinct(c.guidance_user_id)) 
     from case_guidance c 
    where c.guidance_status = '2' 
     and c.guidance_user_type = 'role.type.jyy' 
     and c.province_id = cg.province_id) as guidance_jyy_cnt, 
    (select count(distinct(c.guidance_user_id)) 
     from case_guidance c 
    where c.guidance_status = '2' 
     and c.guidance_user_type = 'role.type.expert' 
     and c.province_id = cg.province_id) as guidance_expert_cnt, 
    (select count(distinct(c.case_id)) 
     from case_guidance c 
    where c.guidance_status = '2' 
     and c.province_id = cg.province_id) as guidance_case_cnt 
from case_guidance cg 
where cg.province_id is not null 
group by cg.province_id 
order by guidance_cnt desc 

回答

0

CASE更換相關子查詢,以消除所有聯接:

select 
    province_id, 
    count(distinct(case when guidance_status = '2'            then guidance_user_id else null end)) guidance_cnt, 
    count(distinct(case when guidance_status = '2' and guidance_user_type = 'role.type.teacher' then guidance_user_id else null end)) guidance_teacher_cnt, 
    count(distinct(case when guidance_status = '2' and guidance_user_type = 'role.type.jyy'  then guidance_user_id else null end)) guidance_jyy_cnt, 
    count(distinct(case when guidance_status = '2' and guidance_user_type = 'role.type.expert' then guidance_user_id else null end)) guidance_expert_cnt, 
    count(distinct(case when guidance_status = '2'            then case_id   else null end)) guidance_case_cnt 
from case_guidance 
group by province_id; 
order by guidance_cnt desc 

(我故意留下的代碼行超長,這樣的條件會排隊這有助於弄清楚什麼列之間的差異是,並且他們都做着幾乎完全相同的事情。)

+0

謝謝你,喬恩。它確實提高了很多性能,排列條件確實有幫助。你節省了我的一天。 – Simon