SQL查詢的一些小技巧

2022-08-09 01:39:13 字數 1280 閱讀 5310

1.當使用and時,將很可能不為真的條件放在前面.

因為資料庫系統從左到右計算條件,並遵守運算子的優先順序.如果乙個條件中存在兩個或多個and運算子,則左邊的乙個條件首先被計算.

例子:1

select

language 

2from

computer

3where

comefrom ='

usa' and

date ='

1990-09-01

'這個查詢可被正確執行,但是日期為1990-09-01的語言較少可能,所以應將date放在comeform前,這樣當第乙個條件不為真時,就不需要再去驗證第二個條件

1select

language 

2from

computer

3where

date =

'1990-09-01

' and

comefrom ='

usa'

2.當使用or運算子時,將最可能為真的條件放在前面.

根據上面and例子,可以推測得原因,使用or運算子時,若一條為真,則為真.其後的都不需要再去驗證

1select

language 

2from

computer

3where

comefrom ='

usa' or

date ='

1990-09-01

'3.對子查詢使用in運算子

考慮下面兩個例子

1select

categoryname 

2from

categories

3where

categoryid =(

select

categoryid 

from

products 

where

productid =10)45

select

categoryname 

6from

categories

7where

categoryid in(

select

categoryid 

from

products 

where

productid =10

)如果使用in運算子重新編寫這個查詢,則資料庫系統僅需要得到與子查詢所返回的值匹配的結果,就可以結束搜尋;

SQL一些小技巧

1.把某個字段重新生氣序列 從1到n declare i int set i 0 update table1 set i i 1,field1 i 2.按成績排名次 update 成績表 set a.名次 select count 1 from 成績表 b where a.總成績 b.總成績 fro...

SQL一些小技巧

1.把某個字段重新生氣序列 從1到n declare i int set i 0 update table1 set i i 1,field1 i 2.按成績排名次 update 成績表 set a.名次 select count 1 from 成績表 b where a.總成績 b.總成績 fro...

sql一些小查詢語句

1.表內容 2005 05 09 勝 2005 05 09 勝 2005 05 09 負 2005 05 09 負 2005 05 10 勝 2005 05 10 負 2005 05 10 負 如果要生成下列結果,該如何寫sql語句?勝 負 2005 05 09 2 2 2005 05 10 1 2...