[英]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? 不使用外键时如何为引用外键的列赋予默认值,例如NULL或0? I am using MySQL and XAMPP for my tables. 我正在为表使用MySQL和XAMPP。
Declare the column as nullable. 将该列声明为可为空。
Then use NULL in the column when you aren't using the foreign key. 当您不使用外键时,在列中使用NULL。
First, if its a key it can not be optional also can not be null/default, its simple logic. 首先,如果它的键不能为可选键,也不能为null / default,则其逻辑简单。 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: 我不记得要怎么做,但是您可以创建一组键(组合键),然后您可以设置一对默认值,以确保其中至少一个是uniq:
<key1.a , 0 >,
<key1.b , 0 >,
< 0 , key2.a >,
< 0 , key2.b >,
<key1.a , key2.b >,
<key1.a , key2.c >,etc...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.