这看起来应该很容易,但事实并非如此。我正在将查询从 MySQL 迁移到 Redshift,格式如下:
INSERT INTO table
(...)
VALUES
(...)
ON DUPLICATE KEY UPDATE
value = MIN(value, VALUES(value))
对于我们要插入但表中还没有的主键,它们只是被插入了。对于表中已有的主键,我们根据取决于行中现有值和新值的条件更新行的值。
http://docs.aws.amazon.com/redshift/latest/dg/merge-replacing-existing-rows.html不起作用,因为在我的例子中 filter_expression
取决于表中的当前条目。我目前正在创建一个暂存表,使用 COPY
语句插入其中,并试图找出合并暂存表和真实表的最佳方法。
最佳答案
我现在必须为一个项目做这件事。我使用的方法包括 3 个步骤:
1.
运行更新以解决更改的字段(我正在更新字段是否已更改,但您当然可以限定):
update table1 set col1=s.col1, col2=s.col2,...
from table1 t
join stagetable s on s.primkey=t.primkey;
2.
运行寻址新记录的插入:
insert into table1
select s.*
from stagetable s
left outer join table1 t on s.primkey=t.primkey
where t.primkey is null;
3.
将源中不再存在的行标记为非事件(我们的报告工具使用过滤非事件记录的 View ):
update table1
set is_active_flag='N', last_updated=sysdate
from table1 t
left outer join stagetable s on s.primkey=t.primkey
where s.primkey is null;
关于sql - 批量更新 Redshift 中的现有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22543093/