【问题标题】:Why composite of primary key with other (not null) columns not automatically unique in PostgreSQL? [duplicate]为什么将主键与其他(非空)列组合在 PostgreSQL 中不会自动唯一? [复制]
【发布时间】:2019-04-23 07:38:49
【问题描述】:

在 PostgreSQL 中使用以下查询创建两个表时:

 create table test_unique_pk (
    id serial primary key,
    value varchar not null
 );

 create table refer_unique_pk (
    id integer,
    value varchar,
    foreign key (id, value) references test_unique_pk(id, value)
 );

我明白了

there is no unique constraint matching given keys for referenced table "test_unique_pk".

如果我将第一个表修改为

 create table test_unique_pk (
     id serial primary key,
     value varchar not null,
     unique(id, value)
 );

效果很好。

但是由于主键已经是唯一的,在我看来,复合(id, value)也应该是唯一的,因为我们不能构造两个具有相同id的元组,因此我们不能构造两个相等的@987654326元组@。

如果上面的说法是正确的,为什么PostgreSQL没有自动对包括主键在内的复合引用添加唯一约束?

【问题讨论】:

  • 如果id 已经是唯一的,为什么还要将value 列作为外键的一部分添加?
  • 因为这是他们定义语言的方式。这个问题不问设计师是无法回答的。如果您只想确认唯一列集的超集是唯一的,请编辑您的问题以提出该问题,并且您是正确的。
  • @a_horse_with_no_name,我需要保持表test_unique_pk 和表refer_unique_pk 具有相同的idvalue。因此数据库应该拒绝像test_unique_pk(id = 3, value="test"), refer_unique_pk(id = 3, value="other")这样的行。
  • 为避免重复,value 列不应出现在refer_unique_pktest_unique_pk 表之一中。 id 列足以确保唯一性,因此如果您需要该值,则应通过连接获取它。

标签: database postgresql primary-key unique-constraint


【解决方案1】:

主键的定义是唯一的,同时不能为空。 NULL 值始终类似于“未知”值,因此您不能在 PK 中使用它。

https://www.w3schools.com/sql/sql_primarykey.asp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    相关资源
    最近更新 更多