gpt4 book ai didi

postgresql - Postgres 错误 :duplicate key value violates unique constraint

转载 作者:行者123 更新时间:2023-11-29 11:33:54 25 4
gpt4 key购买 nike

表定义是

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”处或附近有语法错误。

如何使用 insert into 语句使用 where 子句,以便当我使用 php 运行相同的查询时它不会返回错误

列uid是唯一的

最佳答案

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) ;

关于postgresql - Postgres 错误 :duplicate key value violates unique constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9243189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com