在日常項目中經常會遇到查詢第一條或者最后一條數據的情況,針對不同數據庫,我整理了mysql、sqlserver、oracle數據庫的獲取方法。
1、mysql 使用limit
select * from table order by col limit index,rows;
表在經過col排序后,取從index+1條數據開始的rows條數據。
select * from table order by col limit rows;
表示返還前rows條數據,相當於 limit 0,rows
select * from table order by col limit rows,-1;
表示查詢第rows+1條數據后的所有數據。
2、oracle 使用 row_number()over(partition by col1 order by col2)
select row_number()over(partition by col1 order by col2) rnm from table rnm = 1;
表在經過col1分組后根據col2排序,row_number()over返還排序后的結果
3、sql server top
select top n * from table order by col ;
查詢表的前n條數據。
select top n percent from table order by col ;
查詢前百分之n條數據。