Re: Insert data in two columns same table

From: Andreas Kretschmer <andreas(at)a-kretschmer(dot)de>
To: "drum(dot)lucas(at)gmail(dot)com" <drum(dot)lucas(at)gmail(dot)com>
Cc: Postgres General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Insert data in two columns same table
Date: 2016-03-17 02:26:24
Message-ID: 614214072.16213.1458181584452.JavaMail.open-xchange@oxweb01.ims-firmen.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


> >
> Hi Andreas!
>
> Well...
>
> There are two tables that I need to get data from(dm.billables /
> public.ja_mobiusers), and a third table (dm.billables_links) that I need to
> insert data from those two tables.

lets start from here. you have 2 tables:

test=*# select * from source1;
i
---
1
2
3
(3 rows)

test=*# select * from source2;
i
---
1
2
3
(3 rows)

You can combine this 2 tables via cross join:

test=*# select * from source1 cross join (select * from source2) x;
i | i
---+---
1 | 1
1 | 2
1 | 3
2 | 1
2 | 2
2 | 3
3 | 1
3 | 2
3 | 3
(9 rows)

as you can see there are 9 different combinations. You can insert all the
different combinations into a destination table:

test=*# create table destination (s1 int, s2 int);
CREATE TABLE
test=*# insert into destination select * from source1 cross join (select * from
source2) x;
INSERT 0 9
test=*# select * from destination ;
s1 | s2
----+----
1 | 1
1 | 2
1 | 3
2 | 1
2 | 2
2 | 3
3 | 1
3 | 2
3 | 3
(9 rows)

That's all, or? Keep in mind: you have N * M different combinations from the 2
tables.

--
Andreas Kretschmer
http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Andreas Kretschmer 2016-03-17 02:36:34 Re: Insert data in two columns same table
Previous Message John R Pierce 2016-03-17 02:19:03 Re: Insert data in two columns same table