表定义是
create table users (
serial_no integer PRIMARY KEY DEFAULT nextval('serial'),
uid bigint NOT NULL,
username varchar(32),
name text,
CONSTRAINT production UNIQUE(uid)
);
Run Code Online (Sandbox Code Playgroud)
我用过这个查询
INSERT INTO users (uid) values(123) ;
Run Code Online (Sandbox Code Playgroud)
它表示重复键值违反了唯一约束.所以我用Google搜索并发现了这个链接
所以我试过了
INSERT INTO users (uid) values(123)
where 1 in (select 1 from users where uid = 123) ;
Run Code Online (Sandbox Code Playgroud)
它在"WHERE"或附近说yntax错误.
如何使用insert子句来使用where子句,这样当我使用php运行相同的查询时,它不会返回错误
列uid是独一无二的
在INSERT语句不支持WHERE子句.运行这个.
create table test (
n integer primary key
);
insert into test values (1);
insert into test values (2) where true;
Run Code Online (Sandbox Code Playgroud)
由于WHERE子句,这将给您一个语法错误.
但是,SELECT语句可以有一个WHERE子句.这将在测试表中插入2次.根据需要多次运行; 它不会引发错误.(但它最多只插入一行.)
insert into test (n)
select 2 where 2 not in (select n from test where n = 2);
Run Code Online (Sandbox Code Playgroud)
所以你的查询,假设你试图避免在重复键上引发错误,应该是这样的.
INSERT INTO users (uid)
SELECT 123 WHERE 123 not in (SELECT uid FROM users WHERE uid = 123) ;
Run Code Online (Sandbox Code Playgroud)