I have created two tables. First is 'buildings' and second is 'rooms'.
CREATE TABLE buildings (
building_no int(11) NOT NULL AUTO_INCREMENT,
building_name varchar(255) NOT NULL,
address varchar(355) NOT NULL,
PRIMARY KEY (building_no)
) ENGINE=InnoDB;
CREATE TABLE rooms (
room_no int(11) NOT NULL AUTO_INCREMENT,
room_name varchar(255) NOT NULL,
building_no int(11) NULL,
PRIMARY KEY (room_no),
KEY building_no (building_no),
CONSTRAINT rooms_ibfk_1
DEFAULT NULL
FOREIGN KEY (building_no)
REFERENCES buildings (building_no)
ON DELETE RESTRICT
ON UPDATE CASCADE
) ENGINE=InnoDB;
So when I add a new room with NULL column 'building_no' I get a message:
Cannot add or update a child row: a foreign key constraint fails (
rooms
, CONSTRAINTrooms_ibfk_1
FOREIGN KEY (building_no
) REFERENCESbuildings
(building_no
) ON UPDATE CASCADE)
Why does this happen and how to solve it?