加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

sql – Postgres毗连表的独一多列索引

发布时间:2021-04-02 14:39:35 所属栏目:编程 来源:网络整理
导读:我在Postgres中有一个多对多的毗连表,我想索引到A)进步机能(显然)和B)逼迫独一性.譬喻: a_id | b_id1 | 2 - okay1 | 3 - okay2 | 3 - okay1 | 3 - not okay (same as row 2) 是否可以在两列上行使单个索引来逼迫值中的独一性?我应该行使什么范例的索引? 解

我在Postgres中有一个多对多的毗连表,我想索引到A)进步机能(显然)和B)逼迫独一性.譬喻:

a_id | b_id
1    | 2     <- okay
1    | 3     <- okay
2    | 3     <- okay
1    | 3     <- not okay (same as row 2)

是否可以在两列上行使单个索引来逼迫值中的独一性?我应该行使什么范例的索引?

办理要领

作为主键

假如独一是主键,请执行此操纵:

create table tbl(
   a_id int not null,b_id int not null,constraint tbl_pkey primary key(a_id,b_id)
);

不是主键

假如该独一长短主键,请执行此操纵:

create table tbl(

   -- other primary key here,e.g.:
   -- id serial primary key,a_id int not null,constraint tbl_unique unique(a_id,b_id)
);

现有表格

假如您有现有表,请改为:

alter table tbl
      add constraint tbl_unique unique(a_id,b_id)

alter table表现以下动静:

NOTICE:  ALTER TABLE / ADD UNIQUE will create implicit index "tbl_unique" for table "tbl"


Query returned successfully with no result in 22 ms.

降落

假如您想删除该束缚(您也许但愿将3个字段组合成独一):

ALTER TABLE tbl DROP CONSTRAINT tbl_unique;

指数&束缚&空值

关于索引,来自Postgres doc:

PostgreSQL automatically creates a unique index when a unique
constraint or primary key is defined for a table

资料来历:http://www.postgresql.org/docs/9.1/static/indexes-unique.html

假如独一性取决于某些法则,则应行使CREATE UNIQUE INDEX,譬喻:

鉴于这种:

CREATE TABLE tbl
(
  a_id integer NOT NULL,b_id integer NULL  
);

alter table tbl
    add constraint tbl_unique unique(a_id,b_id);

独一可以捕捉这些一再项,这将被数据库拒绝:

insert into tbl values
(1,1),(1,1);

然而,UNIQUE CONSTRAINT无法捕捉一再的空值. Nulls用作未知数,它们用作通配符,这就是为什么它应承在独一束缚中有多个空值.这将被数据库接管:

insert into tbl values
(1,null),-- think of this null as wildcard,some real value can be assigned later.
(1,null); -- and so is this. that's why both of these nulls are allowed

思量UNIQUE CONSTRAINT它应承耽误独一性,因此接管上面的空值.

假如每个a_id只必要一个通配符(null b_id),除了独一束缚外,还必要添加UNIQUE INDEX. UNIQUE CONSTRAINT不能在它们上面有表达式. INDEX和UNIQUE INDEX可以.这将是您拒绝多个null的完备DDL;

这将是您完备的DDL:

CREATE TABLE tbl
(
  a_id integer NOT NULL,b_id integer NULL  
);
alter table tbl
    add constraint tbl_unique unique(a_id,b_id);

create unique index tbl_unique_a_id on tbl(a_id) where b_id is null;

此刻,您的数据库将拒绝此操纵:

insert into tbl values
(1,null);

这将是应承的:

insert into tbl values
(1,null);

与http://www.ienablemuch.com/2010/12/postgresql-said-sql-server2008-said-non.html有关

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读