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

4 回答 4

27

试试这个:

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) 
于 2012-03-23T08:54:52.623 回答
15

获得 id8后,您应该能够对以下内容进行更改:

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

和:

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

用于上一条和下一条记录。

于 2012-03-23T08:56:33.410 回答
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)

它将表扩展为二维,因此您可以将第一个表中的行与第二个表中的任何行集进行比较。

于 2012-03-23T09:06:34.450 回答
-1
select *
from callvalue
where id <  maxd
(
select max(id) as maxd
from callvalue
where id = maxd
)
于 2014-02-02T03:32:14.070 回答