poll_records テーブルに基づいて users テーブルの number_of_votes を更新したいと考えています。レールでは、次のようになります
User.all.each do |user|
user.number_of_votes = user.poll_records.where("poll_record_type = 3").size
user.save
end
私はPostgreSQLが初めてです。この方法でユーザーを更新するにはどうすればよいですか?
poll_records テーブルに基づいて users テーブルの number_of_votes を更新したいと考えています。レールでは、次のようになります
User.all.each do |user|
user.number_of_votes = user.poll_records.where("poll_record_type = 3").size
user.save
end
私はPostgreSQLが初めてです。この方法でユーザーを更新するにはどうすればよいですか?
次のようになります。
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"(予約語) または大文字と小文字が混在する識別子をテーブル名として使用しません。二重引用符を強制します。