当您插入一行(Postgresql> 9.5),并且您希望可能的INSERT与可能的UPDATE完全相同时,可以这样写:
INSERT INTO tablename (id,username,password,level,email) VALUES (1,'John','qwerty',5,'john@mail.com') ON CONFLICT (id) DO UPDATE SET id=EXCLUDED.id,username=EXCLUDED.username,password=EXCLUDED.password,level=EXCLUDED.level,email=EXCLUDED.email
有更短的路吗?要说:使用所有的EXCLUDE值。
在sqlite中我曾经做过:
INSERT OR REPLACE INTO tablename (id,user,email) VALUES (1,'john@mail.com')
Postgres没有实现等同于INSERT或REPLACE。从
原文链接:https://www.f2er.com/postgresql/192902.htmlON CONFLICT
docs(强调我的):
It can be either DO NOTHING,or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
虽然它并没有给你更换的速记,但ON CONFLICT DO UPDATE更为普遍,因为它允许您根据预先存在的数据设置新的值。例如:
INSERT INTO users (id,level) VALUES (1,0) ON CONFLICT (id) DO UPDATE SET level = users.level + 1;