簡體   English   中英

如何在SQL中編寫以下Rails查詢?

[英]How can you write the following Rails Query in SQL?

我有以下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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM