简体   繁体   English

MySQL插入外键引用主ID

[英]Mysql insert with foreign key referring to primary id

Let's say I hava a table 假设我有一张桌子

object: 宾语:

id, primary key auto-increment
obj_id, foreign key (object.id)
val, integer

Is it possible to insert a record with obj_id = id. 是否可以插入obj_id = id的记录。 Not having an error with foreign key constraint? 外键约束没有错误?

Insert into object (val) values (123) 插入对象(值)值(123)

If obj_id allows null then it is ok. 如果obj_id允许为null,则可以。

EDIT: 编辑:

What are you trying to achieve? 您想达到什么目的? You said it is a foreign key then it should be the value from that table. 您说这是一个外键,那么它应该是该表中的值。 If you want another column having same data as your PK value then this column should not be the foreign key and you need to write trigger to update that column or some other approach. 如果您希望另一列具有与PK值相同的数据,则该列不应作为外键,您需要编写触发器以更新该列或其他方法。

是的,那完全可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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