I have a table like so:
id min max version data
1 1 10 1 a
2 11 20 1 b
3 21 30 1 c
4 1 10 2 a
5 11 20 2 b
6 21 30 2 c
min, max represent values of key
. Each (min, max)
row within the given version is guaranteed to have mutually exclusive key intervals.
Suppose I have a key value of 5 which and I want the latest version of data for that key. This means, I want to select row with id = 4.
Normally I want to select the set with the latest version, but sometimes I may specify the version number explicitly.
What I have now is this:
select * from range_table where 5 between `min` and `max` and ver = 2;
Question: is there a way to select max version automatically (max ver), without specifying it explicitly? (By "efficiently" I mean without examining all tables rows.)
To Recreate Table
drop table range_table;
CREATE TABLE `range_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`min` int(11) NOT NULL,
`max` int(11) NOT NULL,
`ver` int(11) NOT NULL default 1,
`data` CHAR NOT NULL,
PRIMARY KEY (`id`),
unique key ver_min_max(ver, `min`, `max`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
insert into range_table (`min`,`max`, ver, data) values
(1, 10, 1, 'a'),
(11, 20, 1, 'b'),
(21, 30, 1, 'c'),
(1, 10, 2, 'a'),
(11, 20, 2, 'b'),
(21, 30, 2, 'd');