2015-10-20 60 views
-2

我使用MYSQL和正在尋找一種方式,只選擇一排它過去和下一行有一個叫做fav_num以「3」我可以選擇具有條件的行嗎?上一行和下一行有條件嗎?

的值。例如我場有6行和兩個字段。這些字段是ID和fav_number。

ID| fav_num 
1 | 3 
2 | 2 
3 | 3 
4 | 7 
5 | 2 
6 | 9 

我想找到一種方法,從那裏以前和下一行有3 一個fav_num表返回ID,然後在此查詢將返回ID 2.

如果我道歉我的問題聽起來很混亂。

+0

你是否專門尋找返回ID = 2的數據,或者這是一個通用規則來獲取數據庫中所有條目的fav_num = 2? – Hexana

+0

ID是否始終連續(沒有間隙)? – Strawberry

回答

0

我覺得這可能是工作..

SELECT id 
    FROM tab t 
WHERE t.id BETWEEN 
     (SELECT MAX(id) FROM tab tp WHERE tp.id < t.id AND tp.fav_num = 3) 
    AND (SELECT MIN(id) FROM tab tn WHERE tn.id > t.id AND tn.fav_num = 3) 
-1
SELECT ID FROM tbl WHERE fav_num BETWEEN '1' AND '3'; 
+0

請解釋它爲什麼可行。 –

0

請試試這個:

SELECT a.id FROM test1 a WHERE 
3=(SELECT fav_num FROM test1 WHERE id = (SELECT MAX(id) FROM test1 WHERE id <a.id)) AND 
3=(SELECT fav_num FROM test1 WHERE id = (SELECT MIN(id) FROM test1 WHERE id >a.id)) ; 


SELECT a.id FROM test1 a WHERE 
EXISTS (SELECT 1 FROM test1 WHERE id = (SELECT MAX(id) FROM test1 WHERE  id <a.id) AND fav_num=3) AND 
EXISTS (SELECT 1 FROM test1 WHERE id = (SELECT MIN(id) FROM test1 WHERE id >a.id) AND fav_num=3) ; 

我不知道有關perfornance。

相關問題