我正在使用MYSQL,我正在寻找一种方法来只选择一行,前一行和下一行有一个名为fav_num的字段,值为'3'
例如,我有6行和2个字段。字段是ID和fav_number。
ID| fav_num
1 | 3
2 | 2
3 | 3
4 | 7
5 | 2
6 | 9
我想找到一种方法从表中返回ID,其中上一行和下一行的fav_num为3。 然后,此查询将返回ID 2。
如果我的问题听起来令人困惑,我道歉。答案 0 :(得分: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 :(得分: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) ;
我不确定这种表现。
答案 2 :(得分:-1)
SELECT ID FROM tbl WHERE fav_num BETWEEN '1' AND '3';
答案 3 :(得分:-1)
http://sqlfiddle.com/#!9/2b6fb0/12
SELECT t1.*
FROM t1
INNER JOIN (SELECT
@d1:=0+@d2 d1,
@d2:=0+@d3 d2,
@d3:=fav_num d3,
@previd:=@id prevID,
@id:=id
FROM (
SELECT *
FROM t1
ORDER BY id) t
) filter
ON filter.d1 = 3
AND filter.d3 = 3
AND t1.id = filter.prevID
;