mySQL中的外键和NULL [英] Foreign keys and NULL in mySQL

查看:26
本文介绍了mySQL中的外键和NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在我的 values 表(值)中有一个列作为 knownValues 表的外键引用,并在需要时让它为 NULL,如示例中所示:

Can I have a column in my values table (value) referenced as a foreign key to knownValues table, and let it be NULL whenever needed, like in the example:

表格:值

 product     type     value     freevalue
 0           1        NULL      100
 1           2        NULL      25
 3           3        1         NULL

表格:类型

 id    name     prefix
 0     length   cm
 1     weight   kg
 2     fruit    NULL

表:已知值

id    Type     name
0     2        banana 

注意:表中的类型 values &knownValues 当然被引用到 types 表中.

Note: The types in the table values & knownValues are of course referenced into the types table.

推荐答案

外键中的 NULL 是完全可以接受的.处理外键中的 NULL 很棘手,但这并不意味着您将此类列更改为 NOT NULL 并在参考表中插入虚拟(N/A"、Unknown"、No Value"等)记录.

NULLs in foreign keys are perfectly acceptable. Dealing with NULLs in foreign keys is tricky but that does not mean that you change such columns to NOT NULL and insert dummy ("N/A", "Unknown", "No Value" etc) records in your reference tables.

在外键中使用 NULL 通常需要您使用 LEFT/RIGHT JOIN 而不是 INNER JOIN.

Using NULLs in foreign keys often requires you to use LEFT/RIGHT JOIN instead of INNER JOIN.

这篇关于mySQL中的外键和NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆