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!