我正在尝试在postgres上执行以下sql查询:
INSERT INTO Works_On (ESSN,PNo,Hours) VALUES ('199112111',3,3)
ON DUPLICATE KEY UPDATE Hours = 3;
但是当我这样做时,我得到一个错误:
psql:test2.sql:2: ERROR: syntax error at or near "ON"
LINE 2: ON DUPLICATE KEY UPDATE Hours = 3;
^
我无法找到错误,非常感谢帮助!
答案 0 :(得分:1)
ON DUPLICATE KEY UPDATE
。您可以运行以下查询。
UPDATE Works_on SET Hours = 3 WHERE ESSN='199112111' AND PNo=3;
INSERT INTO table (id, field, field2)
SELECT '199112111',3,3
WHERE NOT EXISTS (SELECT 1 FROM Works_on WHERE ESSN='199112111' AND PNo=3);
如果已存在UPDATE
ESSN='199112111' AND PNo=3
查询将会成功
如果INSERT
的行不存在, ESSN='199112111' AND PNo=3
查询将会成功。