postgresql 引用 PK 的外键是否需要 NOT NULL 约束?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1363887/
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-09-19 23:50:05  来源:igfitidea点击:

Does a Foreign Key referencing PK need the NOT NULL constraint?

database-designpostgresql

提问by WolfmanDragon

Does a Foreign Key referencing a Primary Key need the NOT NULL constraint in a PostgreSQL database?
The database is highly normalized and will be very large. I do not wish to add extra constraints that will slow down the queries even more if said queries are unneeded.

引用主键的外键是否需要 PostgreSQL 数据库中的 NOT NULL 约束?
数据库是高度规范化的,并且会非常大。如果不需要所述查询,我​​不希望添加额外的约束,这会进一步减慢查询速度。

采纳答案by Charles Bretana

If you want to be able to represent unknown in the FK column of that table, then make it nullable, if it has to have a value, make it Not Null.

如果您希望能够在该表的 FK 列中表示未知,则将其设为可空,如果它必须具有值,则将其设为 Not Null。

You can have as many records as you want in the referencing table with null FK values. The unique constraint is on the rows in the referenced table (Where the PK is) not on the rows in the referencing table (where the FK is).

您可以在引用表中拥有任意数量的具有空 FK 值的记录。唯一约束在引用表(PK 所在的位置)中的行上,而不是在引用表(FK 所在的位置)中的行上。

回答by James Black

A primary key must be unique, and ideally it should be picked by the database, to limit problems with concurrency, so, though it can be unique, for 1 record, every other record must have a value.

主键必须是唯一的,理想情况下它应该由数据库选择,以限制并发问题,因此,尽管它可以是唯一的,但对于 1 条记录,其他每条记录都必须有一个值。

Otherwise, how will you know which row this foreign key relates to if there is more than one match?

否则,如果有多个匹配项,您如何知道此外键与哪一行相关?

So, as New in town mentioned, NULL should be valid, but for one record, as the uniqueness will be the larger issue.

因此,正如 New in town 所提到的,NULL 应该是有效的,但对于一个记录,因为唯一性将是更大的问题。

EDIT: oops, misunderstood the question.

编辑:哎呀,误解了这个问题。

I have put null on foreign keys before, but if you have cascade delete for example then null won't work, unless you have the key in the primary table with a null value.

我之前在外键上设置了 null,但是如果你有级联删除,那么 null 将不起作用,除非你在主表中有一个带有空值的键。