开发者社区> 问答> 正文

PostgreSQL 如何实现 insert or update 的操作?报错

一个表有两个字段 id 和 count , 其中 id 是主键。我要插入数据,如果 id 不存在则插入,如果 id 存在则 count 加一。

PG 里可以用 DO UPDATE SET 来实现:

INSERT INTO table1 (id, count) VALUES (1,1) ON CONFLICT (id) DO UPDATE SET count = count + 1

但是报错:ERROR:  column reference "count" is ambiguous

使用 count = EXCLUED.count + 1 逻辑又不对,官方对 EXCLUED 的解释是:

Note that the special excluded table is used to reference values originally proposed for insertion

那应该怎么写呢??求救!

展开
收起
爱吃鱼的程序员 2020-06-07 18:25:29 1264 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
                        <p>INSERT INTO table1 (id, count) VALUES (1,1) ON CONFLICT (id) DO UPDATE SET count = <strong>table1.</strong>count + 1</p>
    
                    
    
                        <p>改成 </p>
    

    INSERT INTO table1 (id, count) VALUES (1,1) ON CONFLICT (id) DO UPDATE SET count = table1.count + 1

    就可以了,哈哈

                        PostgreSQL on duplicate update https://my.oschina.net/beetlerx/blog/1554475 
                    
    
                            谢谢:)
    
    2020-06-07 18:25:47
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
2023云栖大会:和客户一起玩转PolarDB新特性 立即下载
2023云栖大会:PolarDB for AI 立即下载
2023云栖大会:AnalyticDB PostgreSQL 立即下载

相关镜像