外键引用可以在 PostgreSQL 中包含 NULL 值吗?
Can foreign key references contain NULL values in PostgreSQL?
举个例子
create table indexing_table
(
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
);
下面的表格有区别吗?
Table 1:
create table referencing_table
(
indexing_table_id INTEGER references indexing_table
);
Table 2:
create table referencing_table
(
indexing_table_id INTEGER references indexing_table NOT NULL
);
或者,在 Table 1 的情况下,没有 NOT NULL
约束,我们可以插入包含 NULL
值的记录吗?
对于table 1,这个INSERT语句会成功。如果你运行它100次,它就会成功100次。
insert into referencing_table values (null);
相同的 INSERT 语句将在 table 2.
上失败
ERROR: null value in column "indexing_table_id" violates not-null constraint
DETAIL: Failing row contains (null).
有时您希望外键列可以为空,因为它不是必需的(就像不是公民 table 中的每个 citizen 都上过大学,所以university_id
列可以为空)。在其他情况下,该列不应为空,就像每个 student 都应该与 university_id
相关联一样。
因此,如果您考虑要实现的目标,那么您描述的两个 referencing_table
实际上是非常不同的。
举个例子
create table indexing_table
(
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
);
下面的表格有区别吗?
Table 1:
create table referencing_table
(
indexing_table_id INTEGER references indexing_table
);
Table 2:
create table referencing_table
(
indexing_table_id INTEGER references indexing_table NOT NULL
);
或者,在 Table 1 的情况下,没有 NOT NULL
约束,我们可以插入包含 NULL
值的记录吗?
对于table 1,这个INSERT语句会成功。如果你运行它100次,它就会成功100次。
insert into referencing_table values (null);
相同的 INSERT 语句将在 table 2.
上失败ERROR: null value in column "indexing_table_id" violates not-null constraint DETAIL: Failing row contains (null).
有时您希望外键列可以为空,因为它不是必需的(就像不是公民 table 中的每个 citizen 都上过大学,所以university_id
列可以为空)。在其他情况下,该列不应为空,就像每个 student 都应该与 university_id
相关联一样。
因此,如果您考虑要实现的目标,那么您描述的两个 referencing_table
实际上是非常不同的。