在postgresql中,仅当“ deleted”为假时,如何才能使“ name”唯一?

时间:2019-02-02 16:19:17

标签: sql postgresql postgresql-9.5

我有下表

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")
);

仅当namedeleted时,我想使false唯一吗?

1 个答案:

答案 0 :(得分:1)

您可以使用部分唯一索引:

create unique index punq_prm_project_service_product_and_services
    on prm_project_service_product_and_services(name)
    where not deleted;

documentation中所述,必须使用索引而不是唯一约束来完成此操作:

  

仅覆盖某些行的唯一性限制不能写为唯一性约束,但是可以通过创建唯一的部分索引来实施这种限制。