日期:2014-05-18  浏览次数:20398 次

郁闷。。这两个SQL语句效率竟然差这么多!老手进来瞧瞧
语句1:
SELECT   m.item1,m.item2,m.item3,m.item4,m.item5,
count(1)   AS   个数  
FROM   tmpL   m,E   n    
WHERE   m.item5> 0   and     m.item6   > 0   and
m.item1   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item2   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item3   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item4   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item5   IN   (a,b,c,d,e,f,g,h,i,j)
GROUP   BY   m.item1,m.item2,m.item3,m.item4,m.item5
having   count(1)> 100

语句2:
select   *,个数   from   (
SELECT   m.item1,m.item2,m.item3,m.item4,m.item5,
sum(case   when   m.item1   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item2   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item3   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item4   IN   (a,b,c,d,e,f,g,h,i,j)  
AND     m.item5   IN   (a,b,c,d,e,f,g,h,i,j)   then   1   else   0   end)   AS   个数  
FROM   tmpL   m,E   n    
WHERE   m.item5> 0   and     m.item6   is   NULL
GROUP   BY   m.item1,m.item2,m.item3,m.item4,m.item5
)   m
where   个数> 100

-----------------------------
以下为模拟数据脚本:

drop   table   E
GO

--建表脚本:
create   table   E
(
        id                     int,
        a                       int,
        b                       int,
        c                       int,
        d                       int,
        e                       int,
        f                       int,
        g                       int,
        h                       int,
        i                       int,
        j                       int
)
go
--   模拟生成10万条包含0-10的数据
declare   @i1   int,@i2   int,@i3   int,@i4   int,@i5   int,@i6   int,@i7   int,@i8   int,@i9   int,@i10   int,@x   int,@tt   int
select   @x=1
while   @x <=100000
begin
        select   @tt=cast(rand()*1000   as   int)%15
        select   @i1=(CASE   when   @tt <=10   then   @tt   else   0   end)
        select   @tt=cast(rand()*1000   as   int)%15