1

I have a table FinalTable with these columns:

name, lastName, pesel, position, id_operator

I want to fill my FinalTable with values from 2 other tables:

  • AAA - this table has columns like name, lastName, pesel, position
  • BBB - this table has columns name, id_operator, pesel

I want to join AAA and BBB on the pesel column

insert into FinalTable (name, lastName, pesel, position, id_operator)
    select 
        name, lastName, pesel, position, 
        (select id_operator from BBB b where b.pesel = a.pesel) 
    from 
        AAA a;

How to do that? I'd like to set my last column id_operator to the value from BBB. The SQL query above is incorrect.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Matley
  • 1,953
  • 4
  • 35
  • 73
  • 1
    not sure if you're looking for join between two tables, or union all to have multiple selects. but try which ever fits your needs. EDIT: nvm, this is what you're looking for. http://www.postgresqltutorial.com/postgresql-inner-join/ – Hagai Wild Feb 17 '19 at 16:54

4 Answers4

2

I'd insert a join query:

INSERT INTO FinalTable  (name, lastName, pesel, position, id_operator)
SELECT a.name, a.lastName, a.pesel, a.position, b.id_operator
FROM   AAA a
JOIN   BBB b ON pesel = a.pesel;
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2
insert into FinalTable  (name, lastName, pesel, position, id_operator)
select name, lastName, pesel, position, id_operator from AAA a join BBB b on a.pesel=b.pesel;
Vijiy
  • 1,187
  • 6
  • 21
1

use join between two tables

insert into FinalTable  (name, lastName, pesel, position, id_operator)
select name, lastName, pesel, position, id_operator    
from AAA a join BBB b on b.pesel = a.pesel
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63
1

You could use a inner join

insert into FinalTable  (name, lastName, pesel, position, id_operator)
select  a.name, a.lastName, a.pesel, a.position, b.id_operator 
from AAA a
INNER JOIN BBB b ON  b.pesel = a.pesel 
;
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107