插入带有串行字段的表并使用其未来值

问题描述 投票:2回答:1

我有下表:

CREATE TABLE problem (
  id SERIAL,
  title VARCHAR(50),
  author VARCHAR(50),
  path TEXT,
  compiler VARCHAR(20),
  PRIMARY KEY (id)
);

problem.id是一个自动递增的整数。有一些方法可以在不知道其值的情况下进行插入:

INSERT INTO problem VALUES (DEFAULT, 'Hello World', 'unknown', '/var/www/files/problems', 'Python');
INSERT INTO problem (title, author, path, compiler) VALUES ('Hello World', 'unknown', '/var/www/files/problems', 'Python');

但是,我想在插入时知道problem.id,所以我可以将它附加到path

在/ var / WWW /文件/问题/ {ID}

其中{id}是插入问题的problem.id

postgresql postgresql-8.4
1个回答
7
投票

你可以使用nextval and lastval的组合:

INSERT INTO problem VALUES (
   nextval('problem_id_seq'), 
   'Hello World',
   'unknown', 
   '/var/www/files/problems/' || lastval(), 
   'Python'
);

调用nextval正是Postgres用作SERIAL字段的默认值。因此可以在没有显式nextval调用的情况下编写语句:

INSERT INTO problem VALUES (
   DEFAULT, 
   'Hello World',
   'unknown', 
   '/var/www/files/problems/' || lastval(), 
   'Python'
);
© www.soinside.com 2019 - 2024. All rights reserved.