如何在postgesql中的联接表中复制行?

时间:2019-05-27 11:23:03

标签: sql postgresql

例如,我有两个表main_table和ref_table,它们连接在主表的主键上:

create table table main (
    id serial primary key,
    name varchar(100)
);

create table table_ref (
    main_id bigint references table_main(id),
    vals varchar(100)
);

我要做的是根据ID复制两个表中的行。当我这样做时,它可以工作,但是我不明白如何从table_ref复制vals列:

with copy_main as (
    insert into table_main (name)
        select name 
        from table_main inner join
             table_ref
             on id=main_id
             where id=1
        returning id, 'I need vals from table_ref here!!!' as vals
       )
insert into table_ref (main_id, vals)
    select id, vals
    from copy_main;

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我想你想要这个:

with copy_main as (
    insert into table_main (name)
        select m.name 
        from table_main m
        where m.id = 1
        returning id
       )
insert into table_ref (main_id, vals)
    select cm.id, r.vals
    from copy_main cm cross join
         table_ref r
    where r.main_id = 1;