【问题标题】:how to create a table which inserts two tables having same primary key without duplicates and i need all the data如何创建一个表,该表插入两个具有相同主键且不重复的表,我需要所有数据
【发布时间】:2011-03-16 10:46:09
【问题描述】:

Postgres:

create table stock(item_id int primary key, balance float);
insert into stock values(10,2200);
insert into stock values(20,1900);
select * from stock;

create table buy(item_id int primary key, volume float);
insert into buy values(10,1000);
insert into buy values(30,300);
select * from buy;

结果:

 item_id | balance
---------+---------
      10 |    2200
      20 |    1900
(2 rows)


 item_id | volume
---------+--------
      10 |   1000
      30 |    300
(2 rows)

现在我想要另一个包含这两个表数据的表。 新表有 3 行数据,item_id(10,20,30),没有重复

我需要对此进行查询;通过合并或加入。

【问题讨论】:

    标签: postgresql join merge


    【解决方案1】:

    我猜:

    • 你真的想要一个视图而不是一个表格
    • 'buy'表中的值应该从'stock'中扣除

    所以这就是我认为你所追求的:

    create view v_current_stock as
    select item_id, sum(balance) as balance
    from ( select item_id, balance from stock 
           union all
           select item_id, -volume from buy )
    group by item_id;
    



    编辑:似乎我的猜测有点不对劲(见 cmets)。也许您正在寻找full join
    create view v as
    select * from stock full join buy using (item_id);
    
    
    select * from v;
    
    
     item_id | balance | volume
    ---------+---------+--------
          10 |    2200 |   1000
          20 |    1900 |
          30 |         |    300
    

    【讨论】:

    • 是的,我明白你的意思,但我需要像 item_id |余额|音量 ---------+---------+-------- 10 | 2200 | 1000 20 | 1900 | 30 | | 300 作为输出,我需要插入另一个表,或者可能像你一样查看。
    • 非常感谢您回答我,我正是想要的
    【解决方案2】:

    您可以使用insert into ... select 语法:

    create table mytable(item_id int primary key, balance float, volume float);
    
    insert into mytable
    select distinct stock.item_id, balance, volume
    from stock 
    inner join buy on buy.item_id = stock.item_id;
    

    如果需要,您可以使用不同类型的连接(left joinfull join)。在你的情况下,我认为你需要一个full join,但由于我不确定我会在示例中坚持使用inner join

    【讨论】:

    • 是的,我明白你的意思,但我需要像 item_id |余额|音量 ---------+---------+-------- 10 | 2200 | 1000 20 | 1900 | 30 | | 300 作为输出,我需要像以前一样插入到另一个表中。
    • +1 表示比我猜得好。不过不确定distinctitem_id 在两个表中都是唯一的。
    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多