MySQL选择前后行

14

这是一个示例表格:

Column             | 1st record | 2nd record | 3rd record | 4th record | etc<br />
id (primary)       | 1          | 5          | 8          | 12         | etc<br />
name               | name 1     | name 2     | name 3     | name 4     | etc<br />
date               | date 1     | date 2     | date 3     | date 4     | etc<br />
callValue (unique) | val1       | val2       | val3       | val4       | etc
我选择一个要显示的数据行(例如:callValue为val3的行)。但是我无法找到解决方案:
我需要选择前一行和后一行。 因此,在此示例中,我需要从行callValue:val4和callValue:val2或id:5和id:12获取数据。

使用id=id+-1无法完成此操作,因为由于删除行,id不必连续。

4个回答

26

试一下这个:

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) 
或者
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) 

起初我收到了错误信息,但在 union 后面加上 () 就解决了 :) - bosniamaj
欢迎!很抱歉我不是很擅长mysql特定的语法 :( - Andrey Gurinov

16

一旦你有id 8,你应该能够进行以下变化:

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

而且:

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

获取上一条和下一条记录。


4
这个方案更简洁易懂,适合所有人理解。 - Albi Patozi
3
你怎么知道这对每个人都更好?你可能是指这对你自己更好。 - Jure Špik
3
它更短,使用了更简单的语法,更易读,并且具有卓越的性能。我认为可以说它整体上更好。 - Luciasar
@JureŠpik,来吧,很明显这个答案比被接受的答案更好。 - Wesley Brian Lachenal
是的,但对于我来说,另一个答案更好,并不是“对每个人都更好”。 - Spikolynn

2

这个可以工作:

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)

它将表格扩展为二维,这样您就可以将第一张表格的行与第二张表格的任何一组行进行比较。


-1
select *
from callvalue
where id <  maxd
(
select max(id) as maxd
from callvalue
where id = maxd
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接