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

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

问题描述

我可以在我的值表(值)中引用一个列作为knownValues表的外键,并在需要时将其设置为NULL,如下例所示:



表:值

 产品类型值freevalue 
0 1 NULL 100
1 2 NULL 25
3 3 1 NULL

表:类型

  id名称前缀
0长度厘米
1重量kg
2水果NULL
pre>

表:knownValues

  id类型名称
0 2香蕉

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

解决方案

外键中的NULL完全可以接受。处理外键中的NULL是棘手的,但这并不意味着您将这些列更改为NOT NULL,并在引用表中插入du​​mmy(N / A,Unknown,No Value等)记录。



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


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:

Table: values

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

Table: types

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

Table: knownValues

id    Type     name
0     2        banana 

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

解决方案

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.

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

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

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