(Ruby 1.9.3-p429;Rails 3.0.6)最近对我们的测试排队方式的更改呈现了我们的 last_ids 范围:
last_ids = tests.where('end_time != 0').
group(:condition1, :condition2, :condition3, :condition4).
select('max(id) as id')
逻辑上已经过时了。以前,测试按创建测试记录的相同顺序排队和完成,因此每个分组的最大 id 也是最新的测试记录。现在,为了提高效率,我们有一个不再保证测试顺序的排队算法。我在测试表中添加了一个“end_time”列。我的解决方案,到目前为止使用起来太慢了:
max_end_times = tests.where('end_time != 0').
group(:condition1, :condition2, :condition3, :condition4).
.maximum(:end_time)
这会产生一个哈希:{[:condition0, :condition1, :condition2, :condition3]=>:endtime}。然后我做如下:
hash.each_pair do |key, value|
last_ids << tests.select(:id).
where(condition0: [key[0]]).
where(condition1: [key[1]]).
where(condition2: [key[2]]).
where(condition3: [key[3]]).
where(end_time: [value]).
map(&:id)[0]
end
这行得通,但它完全太慢了。
那么...有谁知道如何匹配给定分组的 maxumum(:end_time) 但只返回 :id 的?(我需要从数据库中获取每个分组的最新测试的 :ids)。
编辑:澄清。