0

I have two tables

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

now what i want to do is for each entry in table1 add entry in table2

ie if my table 1 has entries

|id | name   |
|1  | First  | 
|2  | Second | 
|3  | Third  | 

I need to create three entries in 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);

and as only foreign key is changed for each new entry, i was wonder is it any possibility to automate this process. Is it possible to achieve with query, or should i look at procedures?

2 Answers 2

5

Use an insert based on a select:

insert into table2 (id,name,table1_id)
select nextval('table2_seq'), 'new entry', t1.id
from table1;
Sign up to request clarification or add additional context in comments.

Comments

0

I struggled to get a "SELECT ... WHERE" in the subquery, likely not enough coffee, but finalised on the below syntax:

insert into table (col1, col2 ...)
select 'staticval1',
r.variable1 from reftable r where r.variable2 = 'Some search term'
...;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.