PostgreSQL 中的外键引用可以包含 NULL 值吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28206232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:46:28  来源:igfitidea点击:

Can foreign key references contain NULL values in PostgreSQL?

postgresqlreferenceforeign-keysprimary-key

提问by Alex

As an example

举个例子

create table indexing_table
(
  id SERIAL PRIMARY KEY,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
);

Is there a difference between the following tables?

下表之间有区别吗?

Table 1:

表格1:

create table referencing_table
(
  indexing_table_id INTEGER references indexing_table
);

Table 2:

表 2:

create table referencing_table
(
  indexing_table_id INTEGER references indexing_table NOT NULL
);

Alternatively, in the case of Table 1, where there is no NOT NULLconstraint, are we allowed to insert records containing NULLvalues?

或者,在表 1 的情况下,没有NOT NULL约束,我们是否允许插入包含NULL值的记录?

回答by Mike Sherrill 'Cat Recall'

For table 1, this INSERT statement will succeed. If you run it 100 times, it will succeed 100 times.

对于表 1,此 INSERT 语句将成功。如果你运行它 100 次,它会成功 100 次。

insert into referencing_table values (null);

The same INSERT statement will fail on table 2.

相同的 INSERT 语句将在表 2 上失败。

ERROR:  null value in column "indexing_table_id" violates not-null constraint
DETAIL:  Failing row contains (null).

回答by richyen

Sometimes you want a foreign keyed column to be nullable because it is not required (just as not every citizenin a citizens table went to a university, so a university_idcolumn can be null). In other cases, the column should not be null, just as every studentlshould be associated with a university_id.

有时您希望外键列可以为空,因为它不是必需的(就像不是Citizens 表中的每个公民都上过大学,因此university_id列可以为空)。在其他情况下,该列不应为空,就像每个学生都应该与 a 相关联一样university_id

Therefore, the two referencing_tables you describe are actually very different, if you consider what you are trying to achieve.

因此,referencing_table如果您考虑要实现的目标,那么您描述的两者实际上是非常不同的。