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
Can foreign key references contain NULL values in PostgreSQL?
提问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 NULL
constraint, are we allowed to insert records containing NULL
values?
或者,在表 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_id
column 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_table
s you describe are actually very different, if you consider what you are trying to achieve.
因此,referencing_table
如果您考虑要实现的目标,那么您描述的两者实际上是非常不同的。