【问题标题】:WHERE NOT EXISTS in PostgreSQL gives syntax errorWHERE NOT EXISTS in PostgreSQL 给出语法错误
【发布时间】:2013-04-05 18:23:56
【问题描述】:

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

【问题讨论】:

  • 如果要防止列中出现重复值,最好在该列中添加unique constraint。 (ALTER TABLE live.users ADD CONSTRAINT age_unique UNIQUE(age) )

标签: sql postgresql postgresql-9.1


【解决方案1】:

改为:

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

【讨论】:

    【解决方案2】:
    INSERT INTO live.users ("website", "age") 
    select 'abc', '123'
    WHERE NOT EXISTS (SELECT age FROM live.users WHERE age = 123);
    

    【讨论】:

      【解决方案3】:

      我在 PLPGSQL 中使用 WHERE field NOT EXISTS 时遇到了一些问题。相反,运行良好的是WHERE field NOT IN,使用后我没有收到任何功能错误。

      【讨论】:

        【解决方案4】:

        我看到你要求 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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-27
          • 1970-01-01
          • 1970-01-01
          • 2021-06-13
          • 2018-01-08
          • 1970-01-01
          • 2018-01-08
          • 1970-01-01
          相关资源
          最近更新 更多