2013-04-05 35 views
5

當試圖使用WHERE NOT EXISTS子句來防止在列age中添加具有重複值的行時,我得到錯誤syntax error at or near "WHERE"PostgreSQL中不存在的地方給出語法錯誤

它爲什麼會拋出語法錯誤?我正在使用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

如果要防止列中出現重複值,最好爲該列添加一個「唯一約束」。 (ALTER TABLE live.users ADD CONSTRAINT age_unique UNIQUE(age)) – 2013-04-05 18:40:23

回答

25

做,而不是:

INSERT INTO live.users ("website", "age") 
SELECT 'abc', 123 
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123); 
+0

非常有幫助謝謝.. – 2017-07-04 01:58:37

3
INSERT INTO live.users ("website", "age") 
select 'abc', '123' 
WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123); 
0

我encountere d在PLPGSQL中使用WHERE field NOT EXISTS時遇到的一些問題。相反,運行良好的是WHERE field NOT IN,使用後我沒有收到功能錯誤。

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