PostgreSQL自定义非空约束
我想在我的一个表字段中添加一个NOTNULL CONSTRAINT,但仅当另一个字段具有某个值时 因此,我有一个PostgreSQL自定义非空约束,sql,postgresql,Sql,Postgresql,我想在我的一个表字段中添加一个NOTNULL CONSTRAINT,但仅当另一个字段具有某个值时 因此,我有一个服务表: services: - id - professional_id - is_master 我想编写一个SQL约束,即无论何时是\u master是falseprofessional\u id都不能为null。我试过这样的方法: CREATE TABLE "services" ( "id" text NOT NULL, "professional_id"
服务
表:
services:
- id
- professional_id
- is_master
我想编写一个SQL约束,即无论何时是\u master
是falseprofessional\u id
都不能为null。我试过这样的方法:
CREATE TABLE "services" (
"id" text NOT NULL,
"professional_id" text REFERENCES professionals ON DELETE CASCADE ON UPDATE CASCADE,
EXCLUDE USING gist (
professional_id WITH =,
) WHERE (NOT is_master),
"is_master" boolean NOT NULL DEFAULT false,
PRIMARY KEY ("id")
);
编写此SQL的正确方法是什么?您可以使用
检查约束:
CREATE TABLE "services" (
"id" text NOT NULL,
"professional_id" text
CHECK (CASE WHEN "is_master" IS FALSE AND "professional_id" IS NULL
THEN FALSE ELSE TRUE END), -- and rest of FK
"is_master" boolean NOT NULL DEFAULT false,
PRIMARY KEY ("id")
);
INSERT INTO services
VALUES (1,1, FALSE);
INSERT INTO services
VALUES (2,1, true);
INSERT INTO services
VALUES (3, null, true);
INSERT INTO services
VALUES (4, null, false);
23514:关系“services”的新行违反了检查约束“services\u check”
您可以使用检查约束来执行此操作。一个简单的例子是:
constraint chk_services_master_professions
check (is_master or professional_id is not null)
注意:此版本假定is_master
从不NULL
——或者NULL
等同于“false”。创建一个触发器以实现检查(非is_master和professional_id非NULL)
?这是最干净的定义,但在看到这一点之前我已经接受了另一个答案。
constraint chk_services_master_professions
check (is_master or professional_id is not null)