【问题标题】:How auto increment id and insert 2 rows如何自动增加 id 并插入 2 行
【发布时间】:2020-09-23 14:46:02
【问题描述】:

我有两个具有一对一关系的表,我想将两行插入到具有相同自动增量 ID 的表中。有可能吗?

create table first
(
    id    bigint primary key,
    value varchar(100) not null
);

create table second
(
    id   bigint references first (id),
    sign boolean
);


insert into first(id, value)
values (-- autoincremented, 'some_value');

insert into second(id, sign)
values (-- the same autoincremented, true);

【问题讨论】:

    标签: sql postgresql select sql-insert


    【解决方案1】:

    您的id 列必须定义为“自动增量”,然后才能使用:

    create table first
    (
        id    bigint generated always as identity primary key,
        value varchar(100) not null
    );
    

    那么就可以使用lastval()获取最后生成的id:

    insert into first(id, value)
    values (default, 'some_value');
    
    insert into second(id, sign)
    values (lastval(), true);
    

    或者如果你想明确:

    insert into first(id, value)
    values (default, 'some_value');
    
    insert into second(id, sign)
    values (currval(pg_get_serial_sequence('first','id')), true);
    

    【讨论】:

    • @a_ 非常感谢。你能写一下如何插入几行吗?可能吗?
    【解决方案2】:

    一个选项使用带有returning 子句的cte:

    with i as (
        insert into first(value) values('some_value')
        returning id
    )
    insert into second(id, sign) 
    select i.id, true from i
    

    这会同时执行两个插入;第一个插入的id 是自动生成的,然后在第二个插入中使用。

    为此,您需要将first 表的id 定义为serial。

    【讨论】:

    • 感谢您的回复。用with插入几对正常吗?
    • @Vlad: 是的,在 Postgres 中没问题(你可以看到 in the documentation)
    猜你喜欢
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 2010-11-06
    • 2019-04-28
    • 2015-03-19
    相关资源
    最近更新 更多