2017-04-11 44 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