SQL查询某条记录相邻信息

来源:百度知道 编辑:UC知道 时间:2024/05/15 12:10:10
查询与李斯文相邻的学生信息(根据StuSeat字段)
数据库表如下:
StuName StuNo StuSex StuAge StuSeat StuAddress
1 张秋丽 S25301 男 18 1 北京海淀
2 李文才 S25301 男 21 2 河南洛阳
3 李斯文 S25301 女 20 3 地址不详
4 欧阳俊雄 S25301 男 23 4 新疆威武

楼上的写法在查询到首纪录获末纪录时可能会出错。
select top 3 * from [tablename]
where StuSeat <= (select StuSeat+1 from [tablename] where StuName='李斯文' order by StuSeat)
order by StuSeat desc

select * from 数据库表 where StuSeat=(select StuSeat from 数据库表 where StuName='李斯文')+1 or StuSeat=(select StuSeat from 数据库表 where StuName='李斯文')-1

select *
from table1 b
where b.stuseat =
(select a.stuseat from table1 a where a.stuname = '李斯文') + 1
union
select *
from table1 b
where b.stuseat =
(select a.stuseat from table1 a where a.stuname = '李斯文') - 1