MySql 通过id获取当前某条数据,并把当前数据的前后两条查询出来
思路:
- 给查询数据每项记录增加一个行号用行号记录查询顺序
- 通过id获取目标记录,返回该记录行号,并把行号存到变量(如@nn)
- 通过变量@nn-1 定位到前一条,通过@nn+1定位后一条
- 然后通过 in 过滤 (@nn, @nn-1, @nn+1)三条记录即可
select * from (select @num:=@num+1 row_num, n.* from news n, (select @num:=0) s order by n.time desc ) a
where a.row_num in (
select @nn:=b.row_num as row_num from (select @num2:=@num2+1 row_num, n.* from news n, (select @num2:=0) s order by n.time desc) b
where b.id=199
union all
select @nn-1 as row_num
union all
select @nn+1 as row_num
);