通过书签查找优化SQL查询速度

时间:2011-08-24 16:57:02

标签: sql query-optimization

由于在执行结束时正在执行的书签查找,我已经使用此查询编写了一些路障。我想知道是否有人有任何建议来解决这个问题。查询如下:

select 
isNull(a.groupname, b.groupname) groupname,  
isNull(a.gName, b.gName) gName,  
isNull(a.sab_count, 0) as sab_count,  
isNull(b.prdb_count, 0) as prdb_count 
from 
( select g.gid, groupname, gName, count(p.pid) as sab_count 
from 
( select  gid, 'g00' + convert(varchar(1), gid) as groupname, gName from groups g where    gid < 10 
union 
select  gid, 'g0' + convert(varchar(2), gid) as groupname, gName from groups g where gid   > 10 and gid < 100 
union 
select  gid, 'g' + convert(varchar(3), gid) as groupname, gName from groups g where gid > 100 ) g, panelists p 
where p.groups like '%' + groupname + '%' and p.validated in (1,2,3,4) 
group by g.gid, groupname, gName ) a 
FULL OUTER JOIN  
( select g.gid, groupname, gName, count(p.prid) as prdb_count 
from 
( select  gid, 'g00' + convert(varchar(1), gid) as groupname, gName from groups g where  gid < 10 
union 
select  gid, 'g0' + convert(varchar(2), gid) as groupname, gName from groups g where gid > 10 and gid < 100 
union 
select  gid, 'g' + convert(varchar(3), gid) as groupname, gName from groups g where gid > 100 ) g, prdb p 
where p.groups like '%' + groupname + '%' 
and p.valid in (0,1)
group by g.gid, groupname, gName ) b on a.gid = b.gid 
order by isNull(a.gName, b.gName)

“和(0,1)中的p.valid”是正在使用书签的地方。基于我读过的其他帖子,我一直在尝试一些不同的东西,但是想知道是否有人有新想法。

1 个答案:

答案 0 :(得分:1)

将此作为案例陈述

select  gid, 'g00' + convert(varchar(1), gid) as groupname, gName from groups g where    gid < 10  
union  
select  gid, 'g0' + convert(varchar(2), gid) as groupname, gName from groups g where gid   > 10 and gid < 100  
union  
select  gid, 'g' + convert(varchar(3), gid) as groupname, gName from groups g where gid > 100 
) -- u r selecting whole table ? u will throw off optimizer 

select gid, case
            when gid < 10 then 'g00'
            when gid < 100 then 'g0'
            when gid > 100 then 'g' 
            end  + .. same follows for convert
from groups g

其实我觉得你甚至不需要一个案子......