简体   繁体   中英

MySQL : How to give a default value to a foreign key when I don't use it?

Right now I have a table that has two foreign key, both that reference to different tables. When I insert a value in one foreign key field, but not in the other one, my insert fails because the foreign key constraint. How can I give a default value, like NULL or 0, to a column that references a foreign key, when I am not using it, or make the foreign key optional? I am using MySQL and XAMPP for my tables.

Declare the column as nullable.

Then use NULL in the column when you aren't using the foreign key.

First, if its a key it can not be optional also can not be null/default, its simple logic. I don't remember how to but you could create a group of keys (composed key) then the pair you can set a default value always that at least one of them is uniq:

<key1.a ,   0   >,
<key1.b ,   0   >,
<   0   , key2.a >,
<   0   , key2.b >,
<key1.a , key2.b >,
<key1.a , key2.c >,etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM