POSTGRESQL :INSERT INTO ... SELECT 与自动生成的列

Som*_*ari 5 sql postgresql sql-insert

我有两个表 A(id, col1, col2) 和 B(col3, col4, col5, col6)

表 A 中的列“id”是自动生成的主键,而不是 null。

要将数据从表 B 插入表 A,我正在尝试

INSERT INTO A(col1, col2)
(SELECT col3, col4 from B)
Run Code Online (Sandbox Code Playgroud)

此语句引发错误

ERROR:  null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, "abc", "def")
Run Code Online (Sandbox Code Playgroud)

我也试过

INSERT INTO A(id, col1, col2)
(SELECT DEFAULT, col3, col4 from B)
Run Code Online (Sandbox Code Playgroud)

这会引发错误

ERROR:  syntax error at or near "DEFAULT"
Run Code Online (Sandbox Code Playgroud)

为什么 postgres 不为列“id”自动生成值?如果我从表 B 中提供“id”,或者如果我插入单行(没有选择)并为自动生成的列提供“DEFAULT”关键字,则查询有效。

编辑:表创建查询

CREATE TABLE A 
(
id bigint NOT NULL, 
col1 character varying(10), 
col2 character varying(10), 
CONSTRAINT A_pk PRIMARY KEY (id) 
); 
ALTER TABLE A OWNER TO user1; 

CREATE SEQUENCE A_id_seq 
START WITH 1 
INCREMENT BY 1 
NO MINVALUE 
NO MAXVALUE 
CACHE 1; 

ALTER TABLE A_id_seq OWNER TO user1; 

ALTER SEQUENCE A_id_seq OWNED BY A.id; 
Run Code Online (Sandbox Code Playgroud)

Gor*_*off 3

不要使用明确的序列。只需将列定义为serialbigserial

CREATE TABLE A (
    id bigserial NOT NULL, 
    col1 character varying(10), 
    col2 character varying(10), 
    CONSTRAINT A_pk PRIMARY KEY (id) 
); 
Run Code Online (Sandbox Code Playgroud)

然后插入就可以了。 是一个 SQL Fiddle。