在 postgresql 中,如何使 "name" 只有在 "deleted" 为 false 时才唯一?
In postgresql, how can I make "name" unique only when "deleted" is false?
我有以下 table
CREATE TABLE "prm_project_service_product_and_services" (
"id" BIGSERIAL NOT NULL,
"name" VARCHAR(60) NOT NULL,
"note" VARCHAR(256) NOT NULL,
"version" BIGINT DEFAULT NULL,
"created_date" TIMESTAMP DEFAULT NULL,
"created_by_id" BIGINT DEFAULT NULL,
"last_modified_date" TIMESTAMP DEFAULT NULL,
"last_modified_by_id" BIGINT DEFAULT NULL,
"deleted" BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY ("id"),
CONSTRAINT project_service_product_and_services_unique UNIQUE ("name")
);
我只想在 deleted
为 false
时使 name
唯一,这可能吗?
您可以使用部分唯一索引:
create unique index punq_prm_project_service_product_and_services
on prm_project_service_product_and_services(name)
where not deleted;
如 documentation 中所述,这必须使用索引而不是唯一约束来完成:
A uniqueness restriction covering only some rows cannot be written as a unique constraint, but it is possible to enforce such a restriction by creating a unique partial index.
我有以下 table
CREATE TABLE "prm_project_service_product_and_services" (
"id" BIGSERIAL NOT NULL,
"name" VARCHAR(60) NOT NULL,
"note" VARCHAR(256) NOT NULL,
"version" BIGINT DEFAULT NULL,
"created_date" TIMESTAMP DEFAULT NULL,
"created_by_id" BIGINT DEFAULT NULL,
"last_modified_date" TIMESTAMP DEFAULT NULL,
"last_modified_by_id" BIGINT DEFAULT NULL,
"deleted" BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY ("id"),
CONSTRAINT project_service_product_and_services_unique UNIQUE ("name")
);
我只想在 deleted
为 false
时使 name
唯一,这可能吗?
您可以使用部分唯一索引:
create unique index punq_prm_project_service_product_and_services
on prm_project_service_product_and_services(name)
where not deleted;
如 documentation 中所述,这必须使用索引而不是唯一约束来完成:
A uniqueness restriction covering only some rows cannot be written as a unique constraint, but it is possible to enforce such a restriction by creating a unique partial index.