sql – Postgres连接表的唯一多列索引

前端之家收集整理的这篇文章主要介绍了sql – Postgres连接表的唯一多列索引前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在Postgres中有一个多对多的连接表,我想索引到A)提高性能(显然)和B)强制唯一性.例如:
  1. a_id | b_id
  2. 1 | 2 <- okay
  3. 1 | 3 <- okay
  4. 2 | 3 <- okay
  5. 1 | 3 <- not okay (same as row 2)

是否可以在两列上使用单个索引来强制值中的唯一性?我应该使用什么类型的索引?

解决方法

作为主键

如果唯一是主键,请执行此操作:

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

不是主键

如果该唯一是非主键,请执行此操作:

  1. create table tbl(
  2.  
  3. -- other primary key here,e.g.:
  4. -- id serial primary key,a_id int not null,constraint tbl_unique unique(a_id,b_id)
  5. );

现有表格

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

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

alter table显示以下消息:

  1. NOTICE: ALTER TABLE / ADD UNIQUE will create implicit index "tbl_unique" for table "tbl"
  2.  
  3.  
  4. Query returned successfully with no result in 22 ms.

下降

如果您想删除该约束(您可能希望将3个字段组合成唯一):

  1. 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,例如:

鉴于这种:

  1. CREATE TABLE tbl
  2. (
  3. a_id integer NOT NULL,b_id integer NULL
  4. );
  5.  
  6. alter table tbl
  7. add constraint tbl_unique unique(a_id,b_id);

唯一可以捕获这些重复项,这将被数据库拒绝:

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

然而,UNIQUE CONSTRAINT无法捕获重复的空值. Nulls用作未知数,它们用作通配符,这就是为什么它允许在唯一约束中有多个空值.这将被数据库接受:

  1. insert into tbl values
  2. (1,null),-- think of this null as wildcard,some real value can be assigned later.
  3. (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:

  1. CREATE TABLE tbl
  2. (
  3. a_id integer NOT NULL,b_id integer NULL
  4. );
  5. alter table tbl
  6. add constraint tbl_unique unique(a_id,b_id);
  7.  
  8. create unique index tbl_unique_a_id on tbl(a_id) where b_id is null;

现在,您的数据库将拒绝此操作:

  1. insert into tbl values
  2. (1,null);

这将是允许的:

  1. insert into tbl values
  2. (1,null);

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

猜你在找的MsSQL相关文章