Database 使用序列生成Postgres URI?
所以我想在postgres数据库的表中创建一列,自动递增一个数字,并将其放在一些数据之后。阿卡 协议表:Database 使用序列生成Postgres URI?,database,postgresql,uri,psql,Database,Postgresql,Uri,Psql,所以我想在postgres数据库的表中创建一列,自动递增一个数字,并将其放在一些数据之后。阿卡 协议表: name | uri | _____________________________ someProtocol | /protocol/1 otherProt | /protocol/2 有没有办法用其他数据创建某种序列?我对博士后专栏创作的了解相当有限 create table protocols ( id serial primary k
name | uri |
_____________________________
someProtocol | /protocol/1
otherProt | /protocol/2
有没有办法用其他数据创建某种序列?我对博士后专栏创作的了解相当有限
create table protocols (
id serial primary key, -- creates a sequence int
name text not null,
uri text
);
create or replace function protocols_set_uri() returns trigger as $$
begin
new.uri = '/' || new.name || '/' || new.id;
return new;
end $$
language plpgsql;
create trigger protocols_set_uri
before insert or update on protocols
for each row execute procedure protocols_set_uri();
例如:
insert into protocols (name) values ('someProtocol');
select * from protocols;
结果:
id name uri
--------------------------------
1 someProtocol /someProtocol/1
例如:
insert into protocols (name) values ('someProtocol');
select * from protocols;
结果:
id name uri
--------------------------------
1 someProtocol /someProtocol/1
您不需要更新任何冗余字段;您可以在需要时计算它们,如以下视图所示:
CREATE TABLE protocols (
id SERIAL PRIMARY KEY -- creates a sequence int
, name text not null
);
INSERT INTO protocols(name) VALUES( 'DNS') ,( 'SMTP') ,( 'HTTP') ;
create VIEW fake_protocols AS
SELECT id, name
, '/protocol/' || id::text AS fake_uri
FROM protocols
;
SELECT * FROM fake_protocols;
输出:
CREATE TABLE
INSERT 0 3
CREATE VIEW
id | name | fake_uri
----+------+-------------
1 | DNS | /protocol/1
2 | SMTP | /protocol/2
3 | HTTP | /protocol/3
(3 rows)
您不需要更新任何冗余字段;您可以在需要时计算它们,如以下视图所示:
CREATE TABLE protocols (
id SERIAL PRIMARY KEY -- creates a sequence int
, name text not null
);
INSERT INTO protocols(name) VALUES( 'DNS') ,( 'SMTP') ,( 'HTTP') ;
create VIEW fake_protocols AS
SELECT id, name
, '/protocol/' || id::text AS fake_uri
FROM protocols
;
SELECT * FROM fake_protocols;
输出:
CREATE TABLE
INSERT 0 3
CREATE VIEW
id | name | fake_uri
----+------+-------------
1 | DNS | /protocol/1
2 | SMTP | /protocol/2
3 | HTTP | /protocol/3
(3 rows)