【问题标题】:Postgres ERROR:duplicate key value violates unique constraintPostgres 错误:重复键值违反唯一约束
【发布时间】:2012-03-03 19:57:52
【问题描述】:

表定义是

create table users (
serial_no integer PRIMARY KEY DEFAULT nextval('serial'),
uid bigint NOT NULL,
username varchar(32),
name text,
CONSTRAINT production UNIQUE(uid)
);

我使用了这个查询

INSERT INTO users (uid) values(123) ;

它说重复的键值违反了唯一约束。所以我用谷歌搜索并找到了这个link

所以我尝试了

INSERT INTO users (uid) values(123) 
where 1 in (select 1 from users where uid = 123) ;

它在“WHERE”处或附近显示语法错误。

如何在 where 子句中使用插入语句,这样当我使用 php 运行相同的查询时,它不会返回错误

列 uid 是唯一的

【问题讨论】:

  • 表定义是什么?错误消息似乎非常清楚。看起来表上有一个唯一约束阻止您插入超过 1 行的 uid = 123
  • 已经有一行 uid 为 123。数据库运行正常。你有什么问题?
  • 如果你执行这个查询,select count(*) from users where uid = 123;,你会得到什么?
  • @AnubhavAgarwal:所以你已经有一个唯一 uid 为 123 的行。为什么要插入两个这样的行,当你试图违反唯一约束时你想发生什么?
  • Postgres 的人不友好!

标签: postgresql


【解决方案1】:

INSERT statement 不支持 WHERE 子句。运行这个。

create table test (
  n integer primary key
);

insert into test values (1);
insert into test values (2) where true;

由于 WHERE 子句,这会给你一个语法错误。

但是,SELECT 语句可以有 WHERE 子句。这会将 2 插入测试表一次。尽可能多地运行它;它不会引发错误。 (但它最多只会插入一行。)

insert into test (n) 
select 2 where 2 not in (select n from test where n = 2);

因此,假设您试图避免在重复键上引发错误,您的查询应该是这样的。

INSERT INTO users (uid) 
SELECT 123 WHERE 123 not in (SELECT uid FROM users WHERE uid = 123) ;

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 2020-05-28
    • 2018-08-16
    • 2020-02-15
    • 2016-07-27
    • 2012-06-20
    • 2016-06-06
    • 2011-10-17
    相关资源
    最近更新 更多