postgresql 登录到另一个表时发生冲突

2024-05-18

我正在使用 PostgreSQL 9.5,并尝试使用批量插入每天插入数百万行:

INSERT INTO "tours" as cst ("adults","country_id", "price") 
VALUES (3, 129, 80), (2, 119,120) 
on conflict (adults, country_id) do 
   update set price = EXCLUDED.price, updated_at = now() 
   where excluded.price < cst.price 
RETURNING ID;

如果价格更低,我会更新行。我想添加else记录未更新价格的条件。像这样的东西:

INSERT INTO "tours" as cst ("adults","country_id", "price") 
VALUES (3, 129, 80), (2, 119,120) 
on conflict (adults, country_id) 
   case when excluded.price < cst.price 
      then 
        do update set price = EXCLUDED.price, updated_at = now() 
      else 
        INSERT INTO "tours_price_logging" (price, created_at) 
        values (EXCLUDED.price, now()) end;

但我对这种情况有错误:

ERROR:  syntax error at or near "case"

我考虑删除条件where excluded.price < cst.price从插入并将此逻辑移动到trigger,但稍后我将使用以下值更新行价格tours_price_logging而且价格可能比当前价格更高。

所以,我想使用 upsert 和批量插入与日志记录。


你需要一个触发器:

create or replace function before_update_on_tours()
returns trigger language plpgsql as $$
begin
    if new.price >= old.price then
        insert into tours_price_logging (price, created_at) 
        values (new.price, now());
        return null;
    end if;
    return new;
end $$;

create trigger before_update_on_tours
before update on tours
for each row execute procedure before_update_on_tours();

当新价格不低于旧价格时,触发器将在日志记录表中插入一行并返回 null,因此不会对游览进行任何更新。 使用触发器,您的查询应该如下所示:

insert into tours as cst (adults,country_id, price) 
values (3, 129, 80), (2, 119, 90) 
on conflict (adults, country_id) do 
   update set price = excluded.price, updated_at = now() 
returning id;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

postgresql 登录到另一个表时发生冲突 的相关文章

随机推荐