仅当值不为null时,插入具有冲突更新的查询

问题描述

我有一个类似这样的查询

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);