从多个来源/表插入

时间:2019-02-17 16:51:19

标签: sql postgresql sql-insert insert-select

我有一个带有这些列的表FinalTable

name, lastName, pesel, position, id_operator

我想用另外2个表中的值填充我的FinalTable

  • AAA-该表具有诸如name,lastName,pesel,position之类的列
  • BBB-该表具有列名称,id_operator,比塞尔

我想加入AAA列上的BBBpesel

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;

该怎么做?我想将最后一列id_operator设置为BBB中的值。上面的SQL查询不正确。

4 个答案:

答案 0 :(得分:2)

我要插入一个联接查询:

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;

答案 1 :(得分: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;

答案 2 :(得分:1)

在两个表之间使用join

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

答案 3 :(得分:1)

您可以使用内部联接

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 
;