我正在 PostgreSQL
中创建一个表,我想添加一些列作为常量列,就像我将这些值定义为零,然后 insert
和 update
无法更改该列值。
此外,在 insert
或 update
查询中使用时也不应该显示任何错误,这可能吗?
示例:
表:
CREATE TABLE tbbt
(
const_col integer NOT NULL DEFAULT 0,
id integer,
val text
)
查询:
insert into tbbt(const_col,id,val) values(5,1,'ABC');
insert into tbbt(const_col,id,val) values(6,2,'AVD');
update tbbt set val ='XZX', const_col = 3 where id =2;
select * from tbbt;
输出:
它返回我
const_col id val
5 1 ABC
3 2 XZX
但我需要
const_col id val
0 1 ABC
0 2 XZX
最佳答案
您可以在触发器中静默设置默认值:
create table test(id int, zero int);
create or replace function test_trigger()
returns trigger language plpgsql as $$
begin
new.zero = 0;
return new;
end $$;
create trigger test_trigger
before insert or update on test
for each row
execute procedure test_trigger();
insert into test values (1, 1), (2, 2);
select * from test
id | zero
----+------
1 | 0
2 | 0
(2 rows)
关于php - 如何在 PostgreSQL 中将列设置为常量字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32985620/