MySQL select before after row

北慕城南 提交于 2019-12-03 06:38:47
Andrey Gurinov

Try this:

select * from test where callValue = 'val3'  
union all  
(select * from test where callValue < 'val3' order by id desc limit 1) 
union all  
(select * from test where callValue > 'val3' order by id asc limit 1) 

or

select * from test where id = 8
union all  
(select * from test where id < 8 order by id desc limit 1) 
union all  
(select * from test where id > 8 order by id asc limit 1) 

Once you have the id 8, you should be able to do a variation on:

select * from mytable
where id < 8
order by id desc
limit 1

and:

select * from mytable
where id > 8
order by id asc
limit 1

for the previous and next record.

This works:

select a.id, a.name, a.date, a.callValue 
FROM
(
    select @r0 := @r0 + 1 as rownum, id, name, date, callValue from TABLE
    , (SELECT @r0 := 0) r0
) a,
(
    select @r1 := @r1 + 1 rownum, id, name, date, callValue from TABLE
    , (SELECT @r1 := 0) r1 
) b
where b.callValue = val3 and b.rownum between (a.rownum-1 and a.rownum+1)

It expands the table into 2 dimensions so you can compare the rows in the fist table to any set of rows from the second.

Omar Indegnos
select *
from callvalue
where id <  maxd
(
select max(id) as maxd
from callvalue
where id = maxd
)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!