postgresql - 插入带有序列字段的表并使用其 future 值

标签 postgresql postgresql-8.4

我有下表:

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/files/problems/{id}

{id}插入的问题的problem.id

最佳答案

您可以使用 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'
);

关于postgresql - 插入带有序列字段的表并使用其 future 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25445319/

相关文章:

sql - Postgres 函数比查询/Postgres 8.4 慢

postgresql - 在没有 Postgis 功能的情况下转储或恢复 Postgresql 数据库

postgreSQL 8.4.20 : How to solve missing oldestXID in pg_control preventing use of pg_upgrade on a legacy CentOS 6. 4 服务器?

sql - PL/pgSQL 中同一函数之间的死锁

perl - DBD::Pg::st 执行失败:错误:列 "***"不存在

postgresql - 根据另一个查询返回的条件在 postgres 中触发不同的查询

postgresql - 如果外键所在的表不存在,如何删除外键?

python - 使用 Postgres 在 Python 中用单引号形成插入语句

python - cursor.fetchall() 只返回函数游标的默认值(不运行 fetch all in)

sql - sql原因计算时间差