MySQL Can Foreign Key Be Null

时间:2016-04-15 11:08:16

标签: mysql

Question

Is it valid to have a Null foreign key? Are there any disadvantages?

Example

 ______        _________________
|  id  |      |   id    | id_fk |
|   1  |      |    1    |   2   |
|   2  |      |    2    |   5   |
|   3  |      |    3    |       |
|   4  |      |    4    |   1   |
|   5  |      |    5    |       |
 ‾‾‾‾‾‾        ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾

1 个答案:

答案 0 :(得分:1)

是的,这是可能的,并且不是不坏的做法。您需要确保在对数据库运行查询时考虑到这一点。如果您尝试使用选择运行内部联接,则将自动排除具有空值的所有行。如果您想要加入该关系,即使外键为null,您也可以使用外连接。

相关问题