tags:

views:

70

answers:

1

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!

+3  A: 
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 |
rudi-moore
@rudi Currently this is returning 2 results for readval=2. Edit Oh I see I think by *"I want to get for a given readVal the last consecutive row:"* the OP means last in each pair not last in the last consecutive pair in the table. In that case this looks like the best answer!
Martin Smith
Yes! That's exactly what I was looking for. Thank you!
Bogdan
Are you sure that you don't need the row with id 15 (val 6) in your result? From your definition of "the last consecutive row" it should be returned too, or? (I'll add an query for that case too)
rudi-moore
That's very nice, thank you! I don't need it atm, but could be useful in other places!
Bogdan