關於SQL內部執行的中top和order by順序先後的論證
首先建立一張如下的表 test
包含三個欄位 id ,birth ,studentId
接下來插入資料:
insert into test values(1,'2012-09-12',213 )
insert into test values(2,'2012-08-12',214 )
insert into test values(3,'2012-10-12',211 )
insert into test values(4,'2012-09-12',256 )
insert into test values(5,'2012-04-12',198 )
insert into test values(6,'2012-04-12',198 )
讀者有興趣,可以去執行以下三條語句,並記錄好結果
select * from test
id birth studentID
1 2012-09-12 213
2 2012-08-12 214
3 2012-10-12 211
4 2012-09-12 256
5 2012-04-12 198
6 2012-04-12 198
select top 4 * from test
id birth studentID
1 2012-09-12 213
2 2012-08-12 214
3 2012-10-12 211
4 2012-09-12 256
select * from test order by birth
5 2012-04-12 198
6 2012-04-12 198
2 2012-08-12 214
1 2012-09-12 213
4 2012-09-12 256
3 2012-10-12 211
如果是top先執行,那麼結果(studentId)為 213 214 211 256 在去排序
如果是order by先執行,那麼結果(studentId)應該是 198 198 214 213
select top 4 * from test
--對於with ties的一個補充。with ties適用於消除select top中有重複的屬性(但是算為了兩個)的一個關鍵字
select top 4 * from test order by birth asc
id birth studentID
5 2012-04-12 198
6 2012-04-12 198
2 2012-08-12 214
1 2012-09-12 213
select top 4 with ties * from test order by birth asc
結果
id birth studentID
5 2012-04-12 198
6 2012-04-12 198
2 2012-08-12 214
1 2012-09-12 213
4 2012-09-12 256