在相同的INSERT期间,另一列中的串行列的参考值 [英] Reference value of serial column in another column during same INSERT

查看:63
本文介绍了在相同的INSERT期间,另一列中的串行列的参考值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有SERIAL主键的表,还有一个ltree列,其值我想作为那些主键的串联.例如

I have a table with a SERIAL primary key, and also an ltree column, whose value I want to be the concatenation of those primary keys. e.g.

id | path
----------
1    1
2    1.2
3    1.2.3
4    1.4
5    1.5

我很好奇是否可以在一个查询中进行这样的插入,例如

I'm curious if there's a way to do such an insert in one query, e.g.

INSERT INTO foo (id, ltree) VALUES (DEFAULT, THIS.id::text)

我可能在这里超出了范围,试图在一个查询中做我应该在两个查询中进行的操作(在事务中分组).

I'm probably overreaching here and trying to do in one query what I should be doing in two (grouped in a transaction).

推荐答案

您可以使用CTE从序列一次中检索值,然后重复使用 :

You could use a CTE to retrieve the value from the sequence once and use it repeatedly:

WITH cte AS (
   SELECT nextval('foo_id_seq') AS id
   )
INSERT INTO foo (id, ltree)
SELECT id, '1.' || id
FROM   cte;

带有数据修改命令的CTE 需要Postgres 9.1或更高版本.

The CTE with a data-modifying command requires Postgres 9.1 or later.

如果不确定序列名称,请使用 pg_get_serial_sequence() 代替:

If you are not sure about the name of the sequence, use pg_get_serial_sequence() instead:

WITH i AS (
   SELECT nextval(pg_get_serial_sequence('foo', 'id')) AS id
   )
INSERT INTO foo (id, ltree)
SELECT id, '1.' || id
FROM   i;

如果表名"foo"在数据库中的所有模式中可能不是唯一的,请对模式进行限定.而且,如果任何名称的拼写都是非标准的,则必须双引号:

If the table name "foo" might not be unique across all schemas in the DB, schema-qualify it. And if the spelling of any name is non-standard, you have to double-quote:

pg_get_serial_sequence('"My_odd_Schema".foo', 'id')


快速测试表明 @Mark的想法

Quick tests indicated @Mark's idea with lastval() might work too:

INSERT INTO foo (ltree) VALUES ('1.' || lastval());

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆