I have 'parent' and 'child' tables. There is a column 'parent_id' in 'child' table and it is a foreign key. 'id' column in 'parent' table is NOT NULL and INT. 'parent_id' is also INT but DEFAULT NULL. So when I add a new row to 'child' with NULL 'parent_id' I get an error message:
Cannot add or update a child row: a foreign key constraint fails (
db
.child
, CONSTRAINTchild_ibfk_1
FOREIGN KEY (parent_id
) REFERENCESparent
(id
) ON DELETE NO ACTION ON UPDATE NO ACTION)
CREATE DATABASE db;
USE db;
CREATE TABLE parent (id INT NOT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT NULL,
parent_id INT NULL DEFAULT NULL,
CONSTRAINT child_ibfk_1 FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB;
INSERT INTO child (id, parent_id) VALUES (1, NULL);