开发者

finding the last consecutive row

I need some help with a query.

I have this simple table:

CREATE TABLE `consecutiv` (
  `id` int(11) NOT NULL auto_increment,
  `readVal` int(11) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1;


insert  into `consecutiv`(`id`,`readVal`) values (1,2),(2,2),(3,2),(5,3),(6,3),(7,3),(8,3),(9,4),(10,5),(11,6),(12,6),(13,2),(14,2),(15,6);

Looks like开发者_运维技巧 this:

id  readVal
    1   2
    2   2
    3   2
    5   3
    6   3
    7   3
    8   3
    9   4
   10   5
   11   6
   12   6
   13   2
   14   2
   15   6

I want to get for a given readVal the last consecutive row:

In the above example that would be:

id: 3 for readVal = 2

id: 8 for readVal = 3

...

I tried with this query:

SELECT consecutiv.id, consecutiv.readVal, c.id, c.readVal  FROM consecutiv 
JOIN consecutiv c ON consecutiv.id = c.id-1
WHERE consecutiv.readVal!=c.readVal ORDER BY consecutiv.id ASC

And it works as long as there are no missing id's in the series. In the above example id no 4 is missing and the query won't return the expected result.

Thank you!


SELECT a.id, a.readVal 
FROM consecutiv a
WHERE a.readVal != 
   (SELECT b.readVal 
    FROM consecutiv b 
    WHERE b.id > a.id 
    ORDER BY id ASC
    LIMIT 1)
ORDER BY a.id;

returns:

 id | readval
----+---------
  3 |       2
  8 |       3
  9 |       4
 10 |       5
 12 |       6
 14 |       2

for the case that the very last row is also needed:

SELECT c.id, c.readVal, c.nextReadVal
FROM 
  (SELECT 
   a.id, a.readVal, 
     (SELECT b.readVal
      FROM consecutiv b 
      WHERE b.id > a.id 
      ORDER BY id ASC 
      LIMIT 1) AS nextReadVal
   FROM consecutiv a) AS c
WHERE readVal != nextReadVal OR nextReadVal IS NULL
ORDER BY c.id;

returns:

 id | readval | nextreadval
----+---------+-------------
  3 |       2 |           3
  8 |       3 |           4
  9 |       4 |           5
 10 |       5 |           6
 12 |       6 |           2
 14 |       2 |           6
 15 |       6 |
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜