1

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');
4

3 回答 3

1

您可以取第一行按 ver desc 排序的...

select * from range_table where 5 between `min` and `max` order by ver desc limit 1;
于 2014-12-29T18:05:10.960 回答
0

请尝试以下操作以始终选择最新版本

select * from range_table where @key between `min` and `max` and ver = (select max (a.ver) as max_ver from range_table as a where @key between a.`min` and a.`max`) 

其中@key 将是给定的键值。

于 2014-12-29T17:48:18.947 回答
0

如果您关心性能,那么根据列的大小和/或选择性,您可以向 min 或 max 列添加索引。如果每个 min-max 的版本数仍然很低,那么您的查询将得到优化。

于 2014-12-29T17:29:13.843 回答