简体   繁体   English

可以将空外键刷新为mysql innodb表中的self表?

[英]can refrence null foreign key to self table in mysql innodb table?

i have comment table which have self relation on id and parent-id column. 我有注释表,它们在id和parent-id列上具有自相关性。
each root comment have NULL value (or 0) on parent-id filed. 每个根注释在parent-id字段中都具有NULL值(或0)。 i try to relate them in phpmyadmin and i do that, but when i insert comment with parent-id of NULL mysql give error. 我尝试在phpmyadmin中关联它们,但我这样做,但是当我插入带有NULL父代ID的注释时mysql给出错误。
can we do such a thing in mysql? 我们可以在mysql中做这样的事情吗?

#1452 - Cannot add or update a child row: a foreign key constraint fails
(`hezar`.`comment`, CONSTRAINT `comment_ibfk_1` FOREIGN KEY (`parent`)    
REFERENCES `comment` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)   

Should be working just fine. 应该工作正常。 But you have to allow NULL values for parent . 但是您必须允许parent值为NULL。 You can't insert 0 because this is a constraint violation. 您不能插入0,因为这是违反约束的情况。 Example: 例:

CREATE TABLE mytable (id INT NOT NULL, ref_id INT, PRIMARY KEY(id), FOREIGN KEY (ref_id) REFERENCES mytable(id) ON DELETE CASCADE) ENGINE=InnoDb;
# working inserts
INSERT INTO mytable VALUES (1, NULL);
INSERT INTO mytable VALUES (2, 1);

# failing insert
INSERT INTO mytable VALUES (3, 0);

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

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