【问题标题】:INSERT INTO from multiple sources/tables从多个源/表中插入
【发布时间】:2019-07-11 03:16:44
【问题描述】:

我有一张表 FinalTable 包含这些列:

name, lastName, pesel, position, id_operator

我想用其他 2 个表中的值填充我的 FinalTable

  • AAA - 此表包含 name、lastName、pesel、position 等列
  • BBB - 此表包含列名称、id_operator、pesel

我想加入AAABBBpesel 专栏

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 查询不正确。

【问题讨论】:

标签: sql postgresql sql-insert insert-select


【解决方案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
JOIN   BBB b ON pesel = a.pesel;

【讨论】:

  • 我收到错误:列引用名称不明确。表 BBB 也有“名称”列。
  • @Matley 您可以完全限定所有列。请参阅我编辑的答案。
【解决方案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;

【讨论】:

    【解决方案3】:

    在两个表之间使用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
    

    【讨论】:

      【解决方案4】:

      你可以使用内连接

      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 
      ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-19
        • 1970-01-01
        • 2019-07-26
        • 2015-08-08
        • 1970-01-01
        相关资源
        最近更新 更多