sql - 如果枚举则 SQL 添加约束,则列不可为空
问题描述
给定一个模式
CREATE TYPE offer AS ENUM ('DISCOUNT', 'COUPON');
CREATE TABLE voucher (
...
offerType offer NOT NULL,
couponCode text
)
有没有办法给优惠券添加一个约束,如果优惠类型是优惠券,那么优惠券代码不能为空,如果优惠类型是折扣,那么优惠券代码必须为空?
解决方案
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需要的部分稍后插入。
推荐阅读
- sip - 以下 sintax rfc 3261 是否兼容?
- c# - WebClient 下载问题“拒绝访问”
- databricks - 如何与 bash 命令行交互?
- python - Python 3.9.1 仅使用带有 or 的第一个 if 语句
- python - 如何更有效地处理 pandas 字符串数据?
- c++ - 针对作业问题修复此 C++ void 函数中的错误的建议
- php - 如何 PDO 查询以检索与数组中的值匹配的行
- .net-core - 提供消费者密钥和共享密钥,然后将其用于身份验证
- c - xcb_poll_for_event 导致 100% 使用一个 cpu 核心
- sap-cloud-sdk - 无法在批处理模式下为 ContactOriginData PATCH 设置强制标头