根据计数更新

时间:2012-10-27 19:39:19

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

我想根据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的新手。如何以这种方式更新用户?

1 个答案:

答案 0 :(得分:4)

可能是这样的:

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"(保留字)或混合大小写标识符用作表名。它强迫双引号。