我的postgres数据库中有一张表,当我描述它时,它看起来是这样的。
Table "public.statistical_outputs"
Column | Type | Modifiers
-------------------+--------------------------+------------------------------------------------------------------
id | bigint | not null default nextval('statistical_outputs_id_seq'::regclass)我想知道如果我使用如下语句,将向id列插入什么值
insert into statistical_outputs VALUES (DEFAULT);我试过这样的事情
select nextval('id') from statistical_outputs;但不起作用。
可能相关的问题:
postgresql sequence nextval in schema
PostgreSQL nextval and currval in same query
这一问题可能重复:
Get the default values of table columns in Postgres?
然而,Chris给出的答案是我想要的答案,而不必查看信息模式(我认为我尝试过了,但没有成功)。
发布于 2014-06-10 02:35:52
没有办法直接做你想做的事情--你不能预览这个值。
想象一下:
regress=> CREATE TABLE crazy (blah integer, rand float4 default random());
CREATE TABLE
regress=> insert into crazy(blah, rand) values (1, DEFAULT);
INSERT 0 1
regress=> select * from crazy;
blah | rand
------+----------
1 | 0.932575
(1 row)random()是一个易失性函数,每次返回不同的值。因此,任何预览值的尝试只会使您得到与将要插入的值不同的值。
nextval也是如此,因为并发事务可能会影响值--即使您直接读取当前序列位置,PostgreSQL也试图阻止您这样做(因为它会产生错误的结果)。用random来思考这个问题比用nextval更明显。
因此,对于易失性默认值,您所能做的就是:
insert中提供值,即调用SELECT nextval('statistical_outputs_id_seq')然后调用INSERT INTO ... VALUES (..., 'the value from nextval()');RETURNING获取生成的值我建议用后者。前者在一般情况下是烦人和困难的,因为缺省值可以是任意的表达式。
RETURNING示例
regress=> insert into crazy(blah, rand) values (1, DEFAULT) RETURNING rand;
rand
----------
0.975092
(1 row)
INSERT 0 1https://stackoverflow.com/questions/24131640
复制相似问题