优化SQL小技巧:在适当的时候使用Union代替OR语句

由于OR语句会引起全表扫描,所以在很多时候OR将大大降低查询速度。在这种情况下就可以使用Union来替代OR实现“或”查询。

 原句:

SELECT   [ ID ]
      ,
[ UserID ]
      ,
[ Realname ]
      ,
[ Sex ]
      ,
[ Age ]
      ,
[ Stature ]
      ,
[ Nation ]
      ,
[ Nativeplace ]
      ,
[ Marry ]
      ,
[ Jobkind ]
      ,
[ Workexp ]
      ,
[ QQ ]
      ,
[ Tel ]
      ,
[ MobilePhone ]
      ,
[ Province ]
      ,
[ Area ]
      ,
[ City ]
      ,
[ HopePay ]
      ,
[ HopeCalling ]
      ,
[ HopeMetier ]
      ,
[ CanWorkTime ]
      ,
[ Culture ]
      ,
[ School ]
      ,
[ Specialty ]
      ,
[ Address ]
      ,
[ Abode ]
      ,
[ Email ]
      ,
[ Description ]
      ,
[ Hits ]
      ,
[ Secrecy ]
      ,
[ AddDateTime ]
      ,
[ ReflashTime ]
      ,
[ IsTop ]
      ,
[ CurrState ]
      ,
[ InBase ]
  
FROM   [ SoXuData ] . [ dbo ] . [ tbJob_Resume ]   WHERE  Specialty = ' 计算机 '   OR  Culture = ' 大专 '  

使用Union的语句:

SELECT   [ ID ]
      ,
[ UserID ]
      ,
[ Realname ]
      ,
[ Sex ]
      ,
[ Age ]
      ,
[ Stature ]
      ,
[ Nation ]
      ,
[ Nativeplace ]
      ,
[ Marry ]
      ,
[ Jobkind ]
      ,
[ Workexp ]
      ,
[ QQ ]
      ,
[ Tel ]
      ,
[ MobilePhone ]
      ,
[ Province ]
      ,
[ Area ]
      ,
[ City ]
      ,
[ HopePay ]
      ,
[ HopeCalling ]
      ,
[ HopeMetier ]
      ,
[ CanWorkTime ]
      ,
[ Culture ]
      ,
[ School ]
      ,
[ Specialty ]
      ,
[ Address ]
      ,
[ Abode ]
      ,
[ Email ]
      ,
[ Description ]
      ,
[ Hits ]
      ,
[ Secrecy ]
      ,
[ AddDateTime ]
      ,
[ ReflashTime ]
      ,
[ IsTop ]
      ,
[ CurrState ]
      ,
[ InBase ]
  
FROM   [ SoXuData ] . [ dbo ] . [ tbJob_Resume ]   WHERE  Specialty = ' 计算机 '  
    
Union
    
SELECT   [ ID ]
      ,
[ UserID ]
      ,
[ Realname ]
      ,
[ Sex ]
      ,
[ Age ]
      ,
[ Stature ]
      ,
[ Nation ]
      ,
[ Nativeplace ]
      ,
[ Marry ]
      ,
[ Jobkind ]
      ,
[ Workexp ]
      ,
[ QQ ]
      ,
[ Tel ]
      ,
[ MobilePhone ]
      ,
[ Province ]
      ,
[ Area ]
      ,
[ City ]
      ,
[ HopePay ]
      ,
[ HopeCalling ]
      ,
[ HopeMetier ]
      ,
[ CanWorkTime ]
      ,
[ Culture ]
      ,
[ School ]
      ,
[ Specialty ]
      ,
[ Address ]
      ,
[ Abode ]
      ,
[ Email ]
      ,
[ Description ]
      ,
[ Hits ]
      ,
[ Secrecy ]
      ,
[ AddDateTime ]
      ,
[ ReflashTime ]
      ,
[ IsTop ]
      ,
[ CurrState ]
      ,
[ InBase ]
  
FROM   [ SoXuData ] . [ dbo ] . [ tbJob_Resume ]   WHERE  Culture = ' 大专 '

但是不是什么时候都适合这样做,如果“或”条件的是相同字段则使用OR语句效率要比较高,原因未明,有空再查资料 

你可能感兴趣的:(Datebase)