我想问一下当我选择“8787”
时如何获取下一个和之前的数据这是表名称的样本数据:
NameId不是自动编号。
NameID RName
6767 Apple
8787 Hallow
8627 Orange
由于
答案 0 :(得分:6)
要获取下一个ID,请丢弃所有不大的ID,按ID对表进行排序,以便下一个ID是第一个ID,然后只获取这一个记录:
SELECT *
FROM MyTable
WHERE NameID > 8787
ORDER BY NameID
LIMIT 1
类似于之前的ID:
SELECT *
FROM MyTable
WHERE NameID < 8787
ORDER BY NameID DESC
LIMIT 1
答案 1 :(得分:-1)
根据CL。的答案,如果你想在一个查询中全部使用它:
select a.*,
(select RName
from t1 b
where b.NameID < a.NameID
order by NameID desc limit 1) as prev_rname,
(select NameID
from t1 b
where b.NameID < a.NameID
order by NameID desc limit 1) as prev_NameID,
(select RName
from t1 c
where c.NameID > a.NameID
order by NameID asc limit 1) as next_rname,
(select NameID
from t1 d
where d.NameID > a.NameID
order by NameID asc limit 1) as next_NameID
from t1 a
order by a.NameID;