V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yuan434356430
V2EX  ›  程序员

求问各位 V 友 PG 库的批量插入问题

  •  1
     
  •   yuan434356430 · 2020-07-22 13:06:29 +08:00 · 1046 次点击
    这是一个创建于 1345 天前的主题,其中的信息可能已经有所发展或是发生改变。

    oracle 迁移到 Pg 过程中,改造 merge 为 with 递归形式,但不清楚怎么改成传入 list 形式; 简化的 sql 如下

    with upsert as (update xxx set state = #{state} 
    where code = #{code} and number = #{number} returning *)
    insert into xxx select #{id}, #{state}, #{code}, #{number}
    where (select count(*) from upsert) = 0;
    
    int merge(DTO dto);
    
    这样可以实现单条数据的 upsert,但是对传入 List<DTO>形式毫无头绪,在此求助广大 V 友~
    
    6 条回复    2020-07-22 15:20:06 +08:00
    yuan434356430
        1
    yuan434356430  
    OP
       2020-07-22 13:40:43 +08:00
    兄弟们我自己找到解决方案了,写法是这样的~

    with upsert as (update xxx set state = case when code= '1' and number = '1' then '1'
    when code= '2' and number = '2' then '2'
    end returning code, number returning *)
    insert into xxx select '1', '1', '1', '1'
    where (select count(*) from upsert where '1' = upsert.code and '1' = upsert.number) = 0
    UNION ALL SELECT '2', '2', '2', '2'
    where (select count(*) from upsert where '2' = upsert.code and '2' = upsert.number) = 0;
    yuan434356430
        2
    yuan434356430  
    OP
       2020-07-22 14:22:45 +08:00
    不过还是有点缺陷,就是 case when 涉及不到的条件会置空
    yuan434356430
        3
    yuan434356430  
    OP
       2020-07-22 14:36:57 +08:00
    加了 where 限定条件,完美
    yjhatfdu2
        4
    yjhatfdu2  
       2020-07-22 15:01:21 +08:00
    pg 支持原生的 upsert,insert into tbl values(xx,xx) on conflict(some_unique_key) do update set xxx=exclude.xxx;
    yuan434356430
        5
    yuan434356430  
    OP
       2020-07-22 15:18:40 +08:00
    @yjhatfdu2 表分区之后不支持 on conflict,哈哈哈哈哈哈哈哈哈哈哈哈
    yuan434356430
        6
    yuan434356430  
    OP
       2020-07-22 15:20:06 +08:00
    领导教我一种方式直接用最朴素的方式,foreach 拼 sql,然后用 pipeline 提交到数据库
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5163 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 01:18 · PVG 09:18 · LAX 18:18 · JFK 21:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.