pg中 on conflict 使用与爬坑

9 篇文章 0 订阅
本文介绍了PostgreSQL的ON CONFLICT语句的使用,强调了在字段同名和无法获取原表数据时的处理方法。通过示例展示了如何在数据不存在时插入,存在时更新,并利用临时表进行复杂操作。同时,提到了excluded关键字在更新过程中的作用。
摘要由CSDN通过智能技术生成

mark一下
on conflict 用法真的很方便,不存在就插入,存在可以更新 可以do nothing,就是用起来要注意几点:

  1. 字段必须完全同名。试了半天不行,改了同名就行。
  2. 拿不到原表的内容。退而求其次用原表做一个内连接就行,取原值然后想怎么玩都行。下面这个例子就是取原值并加上新统计值更新回原表。
  3. 建临时表可以加入很多自己需要的内容,操作空间更大
  4. excluded代表新选择出来的内容。
	insert into plate_no_info  
	select plate_no,total_orders ,first_parking_time,last_parking_time
	from (
	select t1.plate_no,(plate_no_info.total_orders + cnt ) as total_orders,plate_no_info.first_parking_time,t1.last_parking_time
	from (
	select plate_no,count(id) cnt,min(parking_time) first_parking_time,max(parking_time) last_parking_time
	from order_list 
	WHERE created_at > CURRENT_DATE - 1
	and plate_no ~'^[\u2e80-\ua4cf]|[\uf900-\ufaff]|[\ufe30-\ufe4f]'
	GROUP BY plate_no
	) t1,
	plate_no_info
	WHERE 1=1
	AND t1.plate_no = plate_no_info.plate_no
	)
	as t_temp
	on conflict(plate_no) 
-- 	do NOTHING
	do update 
	set 
	total_orders = excluded.total_orders,
	first_parking_time = excluded.first_parking_time,
	last_parking_time = excluded.last_parking_time;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值