gpt4 book ai didi

ruby-on-rails - 使用本地哈希/数组更新许多记录的单个 Postgres 查询

转载 作者:行者123 更新时间:2023-11-29 11:36:01 25 4
gpt4 key购买 nike

我想使用单个查询通过 Ruby 哈希或数组更新我的 Postgres 数据库中的许多记录,而不必遍历每条记录并调用单独的更新。

# {:id => :color}
my_hash = {
1 => 'red',
2 => 'blue',
3 => 'green'
}

我怎么不想这样做,因为它执行三个串行查询:

my_hash.each do |id, color|
MyModel.where(id: id).update_all(color: color)
end

我想怎么做:

MyModel.connection.execute <<-SQL
UPDATE my_models
SET color=something
FROM somehow_using(my_hash)
WHERE maybe_id=something
SQL

最佳答案

你可以使用case:

update my_models
set color = case id
when 1 then 'red'
when 2 then 'blue'
when 3 then 'green'
end;

或者将散列保存在一个单独的表中:

create table my_hash (id int, color text);
insert into my_hash values
(1, 'red'),
(2, 'blue'),
(3, 'green');

update my_models m
set color = h.color
from my_hash h
where h.id = m.id;

还有一个选项,如果你知道如何选择散列作为jsonb:

with hash as (
select '{"1": "red", "2": "blue", "3": "green"}'::jsonb h
)
update my_models
set color = value
from hash, jsonb_each_text(h)
where key::int = id;

OP ruby​​-fying klin 的第三种选择:

sql = <<-SQL
with hash as (
select '#{my_hash.to_json}'::jsonb h
)
update my_models
set color = value
from hash, jsonb_each_text(h)
where key::int = id;
SQL

ActiveRecord::Base.connection.execute(sql)

关于ruby-on-rails - 使用本地哈希/数组更新许多记录的单个 Postgres 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34346511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com