![](/img/trans.png)
[英]SQL: How do I do an update that will only update the values that aren't null?
[英]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
description='joey tribbiani'
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
,這將返回到原始表值,這將分配變為無操作。
你可以使用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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.