[英]How to autofill column based on Serial Primary Key in Postgresql?
I have a table with columns like: 我有一个带有列的表:
inner_id(serial pk) | id(varchar) | name(varchar) | fid(varchar)
I want to send row with only id and name: (id, name) How can I say to Postgresql to complete 'fid' column with value based in serial pk(like string + primary key)? 我想发送仅包含id和name的行:(id,name)我如何对Postgresql说以基于串行pk(例如字符串+主键)的值来完成'fid'列? I want this kind of output:
我想要这种输出:
inner_id(serial pk) | id(varchar) | name(varchar) | fid(varchar)
1 G786k NAME FID-1
2 l7hk NAME FID-2
AS a bonus I send row from python and have to use %s in query 作为奖励,我从python发送行,并且必须在查询中使用%s
UPD. UPD。 I tried run query like:
我试过像这样运行查询:
INSERT INTO table (id, name, fid)
VALUES (%s,%s,%s||TO_CHAR(inner_id));
But I get an error, that i cannot refer to inner_id(primary key) 但是我收到一个错误,我无法引用inner_id(主键)
If you define inner_id as 'serial' Postgres will generate sequence for it. 如果将inner_id定义为“ serial”,则Postgres将为其生成序列。 Generally something like "table_name_column_name-seq".
通常类似于“ table_name_column_name-seq”。 You can then set the default for the "fid" column using the currval of that sequence.
然后,您可以使用该序列的当前时间为“ fid”列设置默认值。
create table soq.ref_to_id( inner_id serial, id text, name text, fid text);
alter table soq.ref_to_id alter column fid set default 'FID-' || currval('soq.ref_to_id_inner_id_seq')::text;
-- insert tast data
insert into soq.ref_to_id(id, name)
values ('G786k', 'Gname')
, ('17hk', '17NAME');
-- check results
select * from soq.ref_to_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.