问题描述
INSERT INTO accounts(id,description,followers_count,friends_count,statuses_count)
VALUES(%s,%s,%s)
ON CONFLICT DO UPDATE
SET description=EXCLUDED.description,followers_count=EXCLUDED.followers_count,friends_count=EXCLUDED.friends_count,statuses_count=EXCLUDED.statuses_count;
现在description,statuses_count
都可以为NULL。我的问题是,是否可以将这些查询更改为仅在这些值不为NULL时更新。
例如,在以下情况下:
description='joey tribbiani'
followers_count=45
friends_count=90
statuses_count=15
不会使用NULL值进行更新。但是如果相反,请进行更新。
解决方法
您可以在COALESCE()
子句中使用SET
:
INSERT INTO accounts(id,description,followers_count,friends_count,statuses_count)
VALUES(%s,%s,%s)
ON CONFLICT DO UPDATE
SET description = COALESCE(EXCLUDED.description,description)
followers_count = COALESCE(EXCLUDED.followers_count,followers_count),friends_count = COALESCE(EXCLUDED.friends_count,friends_count),statuses_count = COALESCE(EXCLUDED.statuses_count,statuses_count);
为insert
指定的值是null
时,此值将退回到原始表值上,从而使分配变为无操作。
您可以使用coalesce():
INSERT INTO accounts(id,%s)
ON CONFLICT DO UPDATE
SET description = coalesce(EXCLUDED.description,accounts.description),followers_count = coalesce(EXCLUDED.followers_count,accounts.followers_count),friends_count = coalesce(EXCLUDED.friends_count,accounts.friends_count),statuses_count = coalesce(EXCLUDED.statuses_count,accounts.statuses_count);