简体   繁体   中英

How can you write the following Rails Query in SQL?

I have the following Rails Query:

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. Any ideas how combing the rails loger into sql is possible?

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} :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM