简体   繁体   English

MySQL:不使用外键时如何给它提供默认值?

[英]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.

相关问题 缺少外键时如何使用默认值 - mysql - How to use default value when foreign key is missing - mysql 为什么MySQL在我没有的表上给我一个外键约束错误? - Why does MySQL give me a foreign key constraint error on a table that I don't have? 如何在mysql中为外键列设置默认值 - How do I set default value for a foreign key column in mysql 如何在MySQL的另一个表中仅选择没有相应外键的行? - How do I select only rows that don't have a corresponding foreign key in another table in MySQL? 何时在MySQL中使用外键 - When to use a foreign key in MySQL MYSQL中外键和主键匹配时如何使用SUM - How to use SUM when foreign key and primary key matched in MYSQL 外键没有默认值 - Foreign key doesn't have a default value Django-如何从要获取对象的表中没有外键的表中获取值? - Django - How to GET value from table where I don't have foreign key in table from which I want to GET object? 当我不使用依赖项“ mysql”%“ mysql-connector-java”%“ 5.1.21”时,我得到“无法连接到数据库[默认]” - I get “Cannot connect to database [default]” when I don't use dependency “mysql” % “mysql-connector-java” % “5.1.21” 当外键不返回任何内容时,如何选择MySQL中的记录? - How can I select records in MySQL when a foreign key doesn't return anything?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM