select 1和select 0進行優化
阿新 • • 發佈:2019-02-18
當我們只關心資料表有多少記錄行而不需要知道具體的欄位值時,類似“select 1 from tblName”是一個很不錯的SQL語句寫法,它通常用於子查詢。這樣可以減少系統開銷,提高執行效率,因為這樣子寫的SQL語句,資料庫引擎就不會去檢索資料表裡一條條具體的記錄和每條記錄裡一個個具體的欄位值並將它們放到記憶體裡,而是根據查詢到有多少行存在就輸出多少個“1”,每個“1”代表有1行記錄,同時選用數字1還因為它所佔用的記憶體空間最小,當然用數字0的效果也一樣。在不需要知道具體的記錄值是什麼的情況下這種寫法無疑更加可取。
下面舉例示範這種寫法的常見用法:
1)列出每個班的學生人數
常規寫法
1 2 |
select class, count (*) as pax from students
group by class;
|
更優寫法
1 2 |
select class, count (1) as pax from students
group by class;
|
2)列出每個班最年輕的學生資料
常規寫法
1 2 3 |
select a.* from students a where not exists(
select b.sid from students b where b.sid=a.sid
and b.date_birth>a.date_birth); |
更優寫法
1 2 3 |
select a.* from students a where not exists(
select 1 from students b where b.sid=a.sid
and b.date_birth>a.date_birth);
|