gpt4 book ai didi

sql - 如何在插入前检索列的实际默认值

转载 作者:行者123 更新时间:2023-11-29 14:21:33 25 4
gpt4 key购买 nike

我的 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 给出的答案是我想要的,而无需查看信息模式(我认为我尝试过但没有奏效)。

最佳答案

无法直接执行您想要的操作 - 您无法预览值。

想象一下:

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 (..., '来自 nextval() 的值');

  • 使用RETURNING获取生成的值

我建议后者。在一般情况下,前者既烦人又困难,因为默认值可以是任意表达式。

RETURNING 示例:

regress=> insert into crazy(blah, rand) values (1, DEFAULT) RETURNING rand;
rand
----------
0.975092
(1 row)

INSERT 0 1

关于sql - 如何在插入前检索列的实际默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24131640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com