我有以下 Rails 查询:
Org.find(:all).each do |org|
Org.update_counters org.id, :users_count => org.users.length
end
出于各种原因,比如性能,我需要用 SQL 编写它,这样我就可以执行 SQL,而不是用户 Rails 来进行更新。有什么想法可以将 rails loger 组合成 sql 吗?
谢谢
最佳答案
这个:
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)
关于sql - 如何在 SQL 中编写以下 Rails 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9389515/