Ale*_*lex 12 postgresql reference foreign-keys primary-key
举个例子
create table indexing_table
(
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
);
Run Code Online (Sandbox Code Playgroud)
下表之间有区别吗?
表格1:
create table referencing_table
(
indexing_table_id INTEGER references indexing_table
);
Run Code Online (Sandbox Code Playgroud)
表2:
create table referencing_table
(
indexing_table_id INTEGER references indexing_table NOT NULL
);
Run Code Online (Sandbox Code Playgroud)
或者,在表1的情况下,没有NOT NULL
约束,我们是否允许插入包含NULL
值的记录?
Mik*_*ll' 29
对于表1,此INSERT语句将成功.如果你运行100次,它将成功100次.
insert into referencing_table values (null);
Run Code Online (Sandbox Code Playgroud)
表2中的相同INSERT语句将失败.
ERROR: null value in column "indexing_table_id" violates not-null constraint DETAIL: Failing row contains (null).
ric*_*yen 11
有时您希望外键列可以为空,因为它不是必需的(就像不是Citizens 表中的每个公民都上过大学,因此university_id
列可以为空)。在其他情况下,该列不应为空,就像每个学生都应该与 a 相关联一样university_id
。
因此,referencing_table
如果您考虑要实现的目标,那么您描述的两者实际上是非常不同的。