仅当值不为空时才插入带有冲突更新的查询

Insert query with update on conflict only when values aren't null

我有一个查询是这样的:

INSERT INTO accounts(id, description, followers_count, friends_count, statuses_count)
VALUES(%s, %s, %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, followers_count, friends_count, statuses_count都可以为NULL。我的问题是是否可以将此查询更改为仅在这些值不为 NULL 时更新。

例如当: description='joey tribbiani' followers_count=45 friends_count=90 statuses_count=15 不要使用 NULL 值进行更新。但是当它反过来时,进行更新。

您可以在 SET 子句中使用 COALESCE()

INSERT INTO accounts(id, description, followers_count, friends_count, statuses_count)
VALUES(%s, %s, %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 时,这会返回到原始的 table 值,这会将赋值变为 no-op.

你可以使用 coalesce():

INSERT INTO accounts(id, description, followers_count, friends_count, statuses_count)
VALUES(%s, %s, %s, %s, %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);