【问题标题】:UPDATE based on count基于计数的更新
【发布时间】:2012-10-27 19:39:18
【问题描述】:

我想根据 poll_records 表更新 users 表中的 number_of_votes。在rails中,它看起来像

User.all.each do |user|
  user.number_of_votes = user.poll_records.where("poll_record_type = 3").size
  user.save
end

我是 PostgreSQL 新手。如何以这种方式更新用户?

【问题讨论】:

    标签: sql ruby-on-rails-3 postgresql count sql-update


    【解决方案1】:

    可能是这样的:

    UPDATE users u
    SET    number_of_votes = p.ct
    FROM  (
       SELECT users_id, count(*) AS ct
       FROM   poll_records
       WHERE  poll_record_type = 3
       GROUP  BY users_id
       ) p
    WHERE    u.users_id = p.users_id
    AND      u.number_of_votes IS DISTINCT FROM p.ct;  -- to avoid empty updates
    

    我不会使用"User"(保留字)或混合大小写标识符作为表名。它强制双引号。

    【讨论】:

    • 附言:在 AND 前加where 1=1
    • @wildplasser:修复了 WHERE 子句,thanx。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多