php - 如何在 PostgreSQL 中将列设置为常量字段?

标签 php sql postgresql

我正在 PostgreSQL 中创建一个表,我想添加一些列作为常量列,就像我将这些值定义为零,然后 insertupdate 无法更改该列值。

此外,在 insertupdate 查询中使用时也不应该显示任何错误,这可能吗?

示例:

表:

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/

相关文章:

sql - 无法在 Postgres 中创建特定列

postgresql - 无法连接到 Windows Server 中的 PostgreSQL

database - 用户表 - redis 或 postgres

javascript - 我怎么能检查字符串是否只匹配到另一个字符串

php - 使用 php 将 xml 转换为 html

php - 使用接受数组的 WHERE 子句进行 SQL 查询

sql - 您如何使用 Oracle Case Statement 测试不等式

macos - Postgres 用户不存在?

php - 通过 URL 传递密码的安全方法?

javascript - Highcharts 多线图不显示多线的工具提示