postgresql postgres中unique index和constaraint unique有什么区别?

zf2sa74q  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(186)

此问题在此处已有答案

Postgres unique constraint vs index(11个回答)
4天前关闭。
第一种保证多个字段唯一的方法是使用约束

  1. create table t
  2. (
  3. id bigserial primary key,
  4. val1 integer,
  5. val2 integer,
  6. unique (val1, val2)
  7. );

字符串
另一方面,我们可以使用唯一索引

  1. create table t
  2. (
  3. id bigserial primary key,
  4. val1 integer,
  5. val2 integer
  6. );
  7. create unique index unique_val1_val2
  8. on t (val1, val2);


这里有什么区别吗?mb他们将以不同的方式使用空值?
我在测试时没有注意到任何差异

ghg1uchk

ghg1uchk1#

从手册:
添加唯一约束将自动在约束中列出的列或列组上创建唯一B树索引。仅覆盖某些行的唯一性限制不能写为唯一约束,但可以通过创建唯一部分索引来强制执行此类限制。
NULL的处理取决于您,NULLS NOT DISTINCT或NULLS DISTINCT。

jw5wzhpr

jw5wzhpr2#

区别是没有 *。它们enforce uniqueness完全相同的方式,它们提供 * 几乎 * 完全相同的索引控制级别:你是对的,其中一个区别与null处理有关。Demo:

  1. create table t
  2. (
  3. id bigserial primary key,
  4. val1 integer,
  5. val2 integer,
  6. unique nulls not distinct (val1 /*desc nulls last*/)
  7. include(val2)
  8. with(fillfactor=100)
  9. using index tablespace pg_default
  10. --where id%2=1
  11. deferrable initially deferred
  12. );

字符串
上面注解掉的部分不能在constraint语法中定义,但它们被等效的index语法所允许,反之亦然:索引不接受deferrability行为规范。

  1. create table t2
  2. (
  3. id bigserial primary key,
  4. val1 integer,
  5. val2 integer
  6. );
  7. create unique index on t2 (val1 desc nulls last)
  8. include(val2)
  9. nulls not distinct
  10. with(fillfactor=100)
  11. tablespace pg_default
  12. where id%2=1
  13. /*deferrable initially deferred*/;


还有第三个选项来强制唯一性,即排除约束:

  1. create table t3
  2. (
  3. id bigserial primary key,
  4. val1 integer,
  5. val2 integer,
  6. exclude (coalesce(val1,-1) desc nulls last with =)
  7. include(val2)
  8. with(fillfactor=100)
  9. using index tablespace pg_default
  10. where (id%2=1)
  11. deferrable initially deferred
  12. );


这一次,虽然它也在引擎盖下使用了索引,但它的工作原理并不相同:
如果所有指定的运算符都测试相等性,这相当于UNIQUE约束,尽管普通的唯一约束会更快。然而,排除约束可以指定比简单相等更通用的约束。
设置多个字段也很困难,因为你需要以某种方式将它们合并为一个(数组,JSON,范围等)。

展开查看全部

相关问题