PostgreSQL 13.4:如何基于另一列值为枚举可空列设置默认值
解决方案
1. 为status列添加动态默认约束
PostgreSQL支持在默认值中使用条件表达式,你可以通过ALTER TABLE语句给status列设置基于type列的默认值:
ALTER TABLE your_table_name ALTER COLUMN status SET DEFAULT CASE WHEN type = 't1' THEN 's1'::your_enum_type ELSE NULL END;
说明:
- 替换
your_table_name为你的实际表名 - 替换
your_enum_type为status列对应的枚举类型名称(比如枚举定义为CREATE TYPE status_enum AS ENUM ('s1', 's2');时,就写status_enum) - 该默认值会在插入新行且不指定status值时自动生效:当type为
t1时,status自动设为s1;其他情况保持null
2. 更新现有数据(可选)
如果需要批量修正表中已有的符合条件的null值,执行以下UPDATE语句:
UPDATE your_table_name SET status = 's1'::your_enum_type WHERE type = 't1' AND status IS NULL;
这条语句会把所有type为t1且status为null的行,将status统一设置为s1。
验证效果
插入测试数据验证逻辑:
-- 插入type为t1的行,不指定status INSERT INTO your_table_name (name, type) VALUES ('test_t1', 't1'); -- 插入type为t2的行,不指定status INSERT INTO your_table_name (name, type) VALUES ('test_t2', 't2');
查询结果会显示:
name | type | status --------|------|------- test_t1 | t1 | s1 test_t2 | t2 | null
内容的提问来源于stack exchange,提问作者Eliran Turgeman
相关产品推荐
相关产品推荐

