Foreign keys and NULL in mySQL

2019-02-12 01:59发布

问题:

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.

回答1:

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.



回答2:

Although you can make foreign key columns nullable I would suggest that it's generally better to design tables without nullable foreign keys. Nulls invariably lead to certain ambiguities and incorrect results but that's doubly a problem if the columns in question are expected to be subject to some constraint.



回答3:

This is a 1 to zero-to-many relationship. I have used this many times with SQL Server. I believe it is possible to do this with MySQL as well.

I prefer to avoid NULLs in my databases because of issues related to data aggregation so, depending on my design, I put an UNKNOWN row in the lookup table.



回答4:

Yes it is quite possible to have a NULL in your foreign-key-constrained column. I just tried it. Bear in mind that if you are not using the InnoDB storage engine, your foreign key constraints will be ignored anyway.



回答5:

Of course, there is a possibilities ti have a NULL values in foreign key, but for that you don't get worry about this, I hope you may used InnoDB as database engine to manage the Key constraints. For this case i suggest to use Left Join or Right Join to get rows from DB and Group By can be used for avoid duplication. Please do not use Inner Join.