[英]How can you write the following Rails Query in SQL?
I have the following Rails Query: 我有以下Rails查询:
Org.find(:all).each do |org|
Org.update_counters org.id, :users_count => org.users.length
end
For various reasons, like performance, I need to write this in SQL, so I can execute SQL, and not user Rails to make the update. 由于各种原因,比如性能,我需要在SQL中编写它,因此我可以执行SQL,而不是用户Rails来进行更新。 Any ideas how combing the rails loger into sql is possible?
任何想法如何将rails loger组合到sql中?
Thanks 谢谢
This: 这个:
Org.update_counters org.id, :users_count => org.users.length
Basically does this: 基本上这样做:
update orgs
set users_count = coalesce(users_count, 0) + #{org.users.length}
where id = #{org.id}
Unrolling one step: 展开一步:
update orgs
set users_count = coalesce(users_count, 0)
+ (select count(*) from org_users where org_id = #{org.id})
where id = #{org.id}
Now you've wrapped that in an Org.find(:all).each
so we just have to push the iteration into the SQL and deal with #{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)
And if you really mean to set the users_count
values rather than increment them: 如果您真的要设置
users_count
值而不是增加它们:
update orgs o
set users_count = (select count(*) from org_users ou where ou.org_id = o.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.