2012-02-22 103 views
1

我有以下的Rails查询:如何在SQL中编写以下Rails查询?

Org.find(:all).each do |org| 
    Org.update_counters org.id, :users_count => org.users.length 
end 

由于种种原因,如性能,我需要在SQL写这个,所以我可以执行SQL,而不是用户的Rails进行更新。任何想法如何梳理轨道爱好者到SQL是可能的?

感谢

回答

3

此:

Org.update_counters org.id, :users_count => org.users.length 

基本上做到这一点:

update orgs 
set users_count = coalesce(users_count, 0) + #{org.users.length} 
where id = #{org.id} 

展开了一步:

update orgs 
set users_count = coalesce(users_count, 0) 
       + (select count(*) from org_users where org_id = #{org.id}) 
where id = #{org.id} 

现在你已经包裹在一个Org.find(:all).each所以我们只需要迭代推入SQL和处理#{org.id}

update orgs o 
set users_count = coalesce(users_count, 0) 
       + (select count(*) from org_users ou where ou.org_id = o.id) 

如果你真的要设置users_count值,而不是增量他们:

update orgs o 
set users_count = (select count(*) from org_users ou where ou.org_id = o.id)