按关联排序列中的列最大值?

时间:2014-06-17 11:55:51

标签: sql ruby-on-rails ruby

现在我的控制器遵循index方法(将实际模型混淆为AlphaBeta以获得清洁度):

def index
  @alphas = Alpha.select('"alphas".*, (SELECT MAX(number) FROM betas WHERE alpha_id = "alphas".id) as max_betas_number')
end

生成的SQL很好,我甚至可以ORDER BY max_betas_number列:

SELECT "alphas".*, (SELECT MAX(number) FROM betas WHERE alpha_id = "alphas".id) as max_betas_number FROM "alphas" ORDER BY max_betas_number DESC

问题#1:这是正确的做法吗?

虽然此查询可以正常工作,但在我尝试.paginate()

之前

然后我的整个select包含在COUNT()中,产生无效的SQL语法:

SELECT COUNT("alphas".*, (SELECT MAX(number) FROM betas WHERE alpha_id = "alphas".id) as max_betas_number) FROM "alphas" ORDER BY max_betas_number DESC

导致:

ERROR:  syntax error at or near "as"
LINE 1: ...(number) FROM betas WHERE alpha_id = "alphas".id) as max_bet...
                                                             ^

问题2:这是will_paginate宝石的问题,还是直接依赖于我的错误index方法{{{{{{ 1}}?

1 个答案:

答案 0 :(得分:0)

在相应的max_betas_number模型中考虑缓存 Alpha。这将使读取查询更简单(并且可能更快,取决于数据量)以每次Beta修改的额外写入为代价。

开箱即用的ActiveRecord在某些关联上有counter_cache option (see section 4.3.2)来处理类似情况:它维护关联的对象&#39;计算父模型中的特殊列,例如<assoc>_count