2012-03-23 89 views
9

後,這是示例表:MySQL的選擇前行

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)。但我找不到解決方案:
我需要選擇上一行和下一行。所以,在這個例子中,我需要從行vallValue獲取數據:VAL4和callValue:VAL2,或ID:5和ID:12

它不能與id = id + -1,因爲id沒有完成必須連續刪除行。

回答

20

試試這個:

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) 
+0

感謝的人,你快:) – bosniamaj 2012-03-23 09:37:02

+0

首先我收到錯誤消息,但把()後,工會解決它:) – bosniamaj 2012-03-23 09:38:18

+0

歡迎您!我並不擅長使用特定於mysql的語法,對不起:( – 2012-03-23 09:39:54

11

一旦你的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

這種解決方案更簡單,更好地理解每個人) – 2012-12-23 01:11:22

+2

你怎麼知道這對每個人都好?你可能是說這對你自己更好。 – 2015-03-31 18:35:44

+2

它更短,它使用更簡單的語法,更具可讀性,並且具有更好的性能,我認爲可以說總體上更好。 – Luciasar 2015-08-10 16:33:34

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) 

它展開的表格到2個維度,因此您可以在拳頭表中的行比較的任何一組從第二排。

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