根据当前记录获取前一条与下一条记录常用 sql语句
為什么80%的碼農都做不了架構師?>>> ??
1.oracle實現主要是用分析函數 lag與lead
SELECT *
FROM (SELECT
??????? id,
??????? LAG(ID)
??????? OVER (
????????? ORDER BY ID ) prevId,
??????? LEAD(ID)
??????? OVER (
????????? ORDER BY ID ) nextId
????? FROM table_name)
WHERE ID = #{id}
2.mysql實現
如果ID是主鍵或者有索引,可以直接查找:
方法一:
查詢上一條記錄的SQL語句(如果有其他的查詢條件記得加上other_conditions以免出現不必要的錯誤):
select * from table_a where id = (select id from table_a where id < {$id} [and other_conditions] order by id desc limit 1) [and other_conditions];
查詢下一條記錄的SQL語句(如果有其他的查詢條件記得加上other_conditions以免出現不必要的錯誤):
select * from table_a where id = (select id from table_a where id > {$id}?[and other_conditions]?order by id asc limit 1) [and other_conditions];
方法二:
查詢上一條記錄的SQL語句((如果有其他的查詢條件記得加上other_conditions以免出現不必要的錯誤))
select * from table_a where id = (select max(id) from table_a where id < {$id} [and?other_conditions]) [and?other_conditions];
查詢下一條記錄的SQL語句(如果有其他的查詢條件記得加上other_conditions以免出現不必要的錯誤):
select * from table_a where id = (select min(id) from table_a where id > {$id} [and?other_conditions]) [and?other_conditions];
3.mssql 實現
上一條記錄的SQL語句:
select?top 1 * from ?table_name?where newsid<id order by newsid DESC
下一條記錄的SQL語句:
select top 1 * from table_name ? where newsid>id order by newsid ASC
語句中的id為當前記錄數據id
轉載于:https://my.oschina.net/VILLE/blog/866339
總結
以上是生活随笔為你收集整理的根据当前记录获取前一条与下一条记录常用 sql语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用INFORMATION_SCHEMA逻
- 下一篇: DFiddler:A HTTP Pack