插入多行和另一个表中的一列

use*_*383 0 sql postgresql

我有两张桌子

 CREATE TABLE table1 (
    id bigint NOT NULL,
    name character varying(255),
    CONSTRAINT table1_pkey PRIMARY KEY (id)
 );

 CREATE TABLE table2 (   
     id bigint NOT NULL,
     name character varying(255),
     table1_id bigint,
     CONSTRAINT table2_pkey PRIMARY KEY (id), 
     CONSTRAINT fk_table1_table2 FOREIGN KEY (table1_id) 
     REFERENCES table1 (id) MATCH SIMPLE
 );
Run Code Online (Sandbox Code Playgroud)

现在我想做的是为 table1 中的每个条目添加 table2 中的条目

即如果我的表 1 有条目

|id | name   |
|1  | First  | 
|2  | Second | 
|3  | Third  | 
Run Code Online (Sandbox Code Playgroud)

我需要在 table2 中创建三个条目

insert into table2 (id,name,table2_id) values (nextval('table2_seq'),'new entry', 1);
insert into table2 (id,name,table2_id) values (nextval('table2_seq'),'new entry', 2);
insert into table2 (id,name,table2_id) values (nextval('table2_seq'),'new entry', 3);
Run Code Online (Sandbox Code Playgroud)

由于每个新条目只更改外键,我想知道是否有可能自动化此过程。是否可以通过查询来实现,或者我应该查看程序?

小智 5

使用基于选择的插入:

insert into table2 (id,name,table1_id)
select nextval('table2_seq'), 'new entry', t1.id
from table1;
Run Code Online (Sandbox Code Playgroud)