简体   繁体   中英

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.
each root comment have NULL value (or 0) on parent-id filed. i try to relate them in phpmyadmin and i do that, but when i insert comment with parent-id of NULL mysql give error.
can we do such a thing in 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 . You can't insert 0 because this is a constraint violation. 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);

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