所以我想在postgres数据库中的表中创建一个列,该列自动递增一个数字并将其放在一些数据之后。 AKA
协议表:
name | uri |
_____________________________
someProtocol | /protocol/1
otherProt | /protocol/2
有没有办法用其他数据创建某种序列?我对postgres列创建的了解非常有限
答案 0 :(得分:0)
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
答案 1 :(得分:0)
您无需更新任何冗余字段;您可以在需要时计算它们,如下面的视图中所示:
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)