PostgreSQL中没有的东西给出了语法错误

时间:2013-04-05 18:23:56

标签: sql postgresql postgresql-9.1

尝试使用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...

4 个答案:

答案 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