如何获取MySQL中特定值之前和之后的行

时间:2016-09-28 09:53:45

标签: mysql

假设MySQL表的结构如下:

(时间戳|值)

(4h00  | 3)  ; 
(5h00  | 5)  ; 
(6h00  | 0)  ; 
(7h00  | 0)  ; 
(8h00  | 2)  ; 
(9h00  |10)  ; 
(10h00 | 0)  ; 
(11h00 | 3)  ;

我希望在出现(Value != 0)(Value = 0)(Value != 0)出现后(Value = 0)的第一行显示行。{/ p>

在这种情况下,查询应返回

(5h00  |  5) ;
(8h00  |  2) ; 
(9h00  | 10) ; 
(11h00 |  3) ;

这是我桌子的结构:

CREATE TABLE IF NOT EXISTS `latency` (
  `key` int(100) NOT NULL AUTO_INCREMENT,
  `idReport` varchar(45) NOT NULL,
  `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `value` float NOT NULL,
  `loss` float NOT NULL,
  PRIMARY KEY (`idReport`,`timestamp`),
  UNIQUE KEY `key` (`key`)
) 

2 个答案:

答案 0 :(得分:0)

SELECT * FROM `table` AS tcurrent
INNER JOIN `table` AS tnext
    ON tnext.timestamp = tcurrent.timestamp+60*60
WHERE tnext.value = 0
    AND tcurrent.value != 0

您可以调整+60*60DATE_ADD 1 HOUR更容易阅读。另外,不要忘记正确索引列(UNIQUE INDEX (timestamp, value)听起来不错)。

答案 1 :(得分:0)

您可以使用行编号逻辑,类似这样的

SELECT T.*
FROM
(
SELECT DISTINCT RN FROM
(
SELECT L.*,
         IF (L.VALUE <> @P , @RN:=@RN+1,@RN) RN ,
         @P:=L.VALUE P
FROM   (SELECT @RN:=0, @P:=0 ) RN,`LATENCY` L
#ORDER BY
) S
WHERE S.VALUE = 0

) S1 


JOIN 
(SELECT L.*,
         IF (L.VALUE <> @P1 , @RN1:=@RN1+1,@RN1) RN ,
         @P1:=L.VALUE P
FROM   (SELECT @RN1:=0, @P1:=0 ) RN,`LATENCY` L
#ORDER BY
)  T
ON S1.RN = T.RN-1 OR S1.RN = T.RN+1

子查询s和s1识别值为0的块,并且连接只是选择相邻的行号。