首页 > 解决方案 > 如果枚举则 SQL 添加约束,则列不可为空

问题描述

给定一个模式

CREATE TYPE offer AS ENUM ('DISCOUNT', 'COUPON');

CREATE TABLE voucher (
...
offerType offer NOT NULL,
couponCode text
)

有没有办法给优惠券添加一个约束,如果优惠类型是优惠券,那么优惠券代码不能为空,如果优惠类型是折扣,那么优惠券代码必须为空?

标签: sqlpostgresqltypessum

解决方案


check ((offerType = 'COUPON' and couponCode is not null) or
       (offerType = 'DISCOUNT' and couponCode is null) or
       (offerType not in ( 'COUPON', 'DISCOUNT'))
      ) 

(offerType not in ( 'COUPON', 'DISCOUNT'))其他offertypes需要的部分稍后插入。


推荐阅读