尝试使用WHERE NOT EXISTS
子句阻止在age
列中添加具有重复值的行时,出现错误syntax error at or near "WHERE"
。
为什么会抛出语法错误?我正在使用Postgresql 9.1。
SQL
INSERT INTO live.users ("website", "age")
values ('abc', '123')
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123);
错误
ERROR: syntax error at or near "WHERE"
LINE 6: WHERE NOT EXISTS (SELECT age FROM live.users W...
答案 0 :(得分:27)
改为:
INSERT INTO live.users ("website", "age")
SELECT 'abc', 123
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123);
答案 1 :(得分:3)
INSERT INTO live.users ("website", "age")
select 'abc', '123'
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123);
答案 2 :(得分:0)
我在PLPGSQL中使用WHERE field NOT EXISTS
时遇到了一些问题。取而代之的是WHERE field NOT IN
,我使用它后没有收到任何功能错误。
答案 3 :(得分:0)
我看到你要求v9.1,但它已经过了4年了,现在从PostgreSQL v9.5 - INSERT开始给你ON CONFLICT … DO NOTHING
选项:
INSERT INTO live.users("website", "age") VALUES('abc', '123') ON CONFLICT ("age") DO NOTHING
值得注意这需要在目标表上设置相应的约束 - 但在大多数情况下,我想你无论如何都会拥有它。否则你会得到:
ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification