程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SqlServer數據庫 >> 關於SqlServer >> 優化SQL小技巧:在適當的時候使用Union代替OR語句

優化SQL小技巧:在適當的時候使用Union代替OR語句

編輯:關於SqlServer

由於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語句效率要比較高,原因未明,有空再查資料 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved