根据当前记录获取前一条与下一条记录常用 sql语句
為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??
1.oracle實(shí)現(xiàn)主要是用分析函數(shù) 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實(shí)現(xiàn)
如果ID是主鍵或者有索引,可以直接查找:
方法一:
查詢上一條記錄的SQL語(yǔ)句(如果有其他的查詢條件記得加上other_conditions以免出現(xiàn)不必要的錯(cuò)誤):
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語(yǔ)句(如果有其他的查詢條件記得加上other_conditions以免出現(xiàn)不必要的錯(cuò)誤):
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語(yǔ)句((如果有其他的查詢條件記得加上other_conditions以免出現(xiàn)不必要的錯(cuò)誤))
select * from table_a where id = (select max(id) from table_a where id < {$id} [and?other_conditions]) [and?other_conditions];
查詢下一條記錄的SQL語(yǔ)句(如果有其他的查詢條件記得加上other_conditions以免出現(xiàn)不必要的錯(cuò)誤):
select * from table_a where id = (select min(id) from table_a where id > {$id} [and?other_conditions]) [and?other_conditions];
3.mssql 實(shí)現(xiàn)
上一條記錄的SQL語(yǔ)句:
select?top 1 * from ?table_name?where newsid<id order by newsid DESC
下一條記錄的SQL語(yǔ)句:
select top 1 * from table_name ? where newsid>id order by newsid ASC
語(yǔ)句中的id為當(dāng)前記錄數(shù)據(jù)id
轉(zhuǎn)載于:https://my.oschina.net/VILLE/blog/866339
總結(jié)
以上是生活随笔為你收集整理的根据当前记录获取前一条与下一条记录常用 sql语句的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 用INFORMATION_SCHEMA逻
- 下一篇: [Snipaste]系统截图工具