在postgresql的with语句中使用insert返回的id

在postgresql的with语句中使用insert返回的id,postgresql,Postgresql,假设您具有以下表结构,您喜欢wikipedia,并且页面的标识和状态存储在不同的表中: create table endUsers ( uuid UUID primary key, created timestamptz default now() ); create table endUserRevisions ( id bigserial primary key, endUser

假设您具有以下表结构,您喜欢wikipedia,并且页面的标识和状态存储在不同的表中:

create table endUsers (
  uuid             UUID         primary key,
  created          timestamptz  default now()
);

create table endUserRevisions (
  id               bigserial    primary key,
  endUser          UUID         not null        references endUsers,
  modified         timestamptz  default now(),
  modifiedBy       UUID         not null        references portalUsers,
  name             text         not null,
  company          text         not null,
  email            text         not null
);

alter table endUsers add column
  latestRevision  bigint        not null        references endUserRevisions;
然后,您希望在该数据库中插入一个全新的用户,如:

with lastID as (
  insert into  endUserRevisions (endUser, name, company, email)
    values ('08e7882c-7596-43d1-b4cc-69f855210d72', 'a', 'b', 'c') returning id)
insert into endUsers (uuid, latestRevision)
  values ('08e7882c-7596-43d1-b4cc-69f855210d72', lastID);

-- or

with revision as (
  insert into  endUserRevisions (endUser, name, company, email)
    values ('08e7882c-7596-43d1-b4cc-69f855210d72', 'a', 'b', 'c') returning *)
insert into endUsers (uuid, latestRevision)
  values ('08e7882c-7596-43d1-b4cc-69f855210d72', revision.id);
这两种变体都会失败

列“lastid”不存在

表“last”的子句条目中缺少


失败的原因是,每个子查询都可以作为表而不是普通值访问周围的上下文。换句话说,必须使用select语句访问它,如:

with revision as (
  insert into  endUserRevisions (endUser, name, company, email)
    values ('08e7882c-7596-43d1-b4cc-79f855210d76', 'a', 'b', 'c') returning id)
insert into endUsers (uuid, latestRevision)
 values ('08e7882c-7596-43d1-b4cc-79f855210d76', (select id from revision));

-- or

with revision as (                                                                                                    
  insert into  endUserRevisions (endUser, name, company, email)                                                       
    values ('08e7882c-7596-43d1-b4cc-79f855210d74', 'a', 'b', 'c') returning id)                                      
insert into endUsers (uuid, latestRevision)                                                                           
  select '08e7882c-7596-43d1-b4cc-79f855210d74', revision.id from revision;