简体   繁体   中英

One to many relationship in SQL - foreign key error

I am trying to create a campus structure. So buildings have floors, floors have rooms. I am trying to create a relational database such that multiple rooms relate to one floor and multiple floors relate to their building.

Here is my structure for the building and floor tables:

CREATE TABLE `building` (
 `id` int(11) NOT NULL,
 `name` varchar(128) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

CREATE TABLE `floor` (
 `id` int(11) NOT NULL,
 `building_id` int(11) DEFAULT NULL,
 `level` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`),
 KEY `floor_building_id__fk` (`building_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

I want to insert more than one floor in the floor table relating to the same building_id using:

INSERT INTO `floor` SET id=3, `number` = 420, building_id=(SELECT id FROM building WHERE id=2);

However I keep getting the following error:

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`seatspace`.`floor`, CONSTRAINT `building_id` FOREIGN KEY (`id`) REFERENCES `building` (`id`))

I want to insert, update and delete floors relating to their specified building_id . Any help would be appreciated.

I have fixed the problem by changing the constraint name for the foreign key. I also rewrote parts of the schema so all of the desired columns were present. Here is the final schema and CRUD.

CREATE TABLE `floor` (
  `floor_id` int(11) NOT NULL AUTO_INCREMENT,
  `number` int(11) NOT NULL,
  `building_id` int(11) NOT NULL,
  PRIMARY KEY (`floor_id`),
  UNIQUE KEY `floor_id_UNIQUE` (`floor_id`),
  KEY `building_id_idx` (`building_id`),
  CONSTRAINT `building_id` FOREIGN KEY (`building_id`) REFERENCES `building` 
(`building_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1

INSERT INTO `floor` (floor_id, `number`, building_id) VALUES (default, 3, 
(SELECT building_id FROM building WHERE building_id=2)) ;
UPDATE `floor` SET `number`=3, building_id=1 WHERE floor_id=2;
DELETE FROM `floor` WHERE floor_id=3;

CREATE TABLE `building` (
  `building_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`building_id`),
  UNIQUE KEY `building_id_UNIQUE` (`building_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1

INSERT INTO building (building_id, name) VALUES (DEFAULT, '1 West');
UPDATE `building` SET `name`='3 West' WHERE building_id=2;
DELETE FROM `building` WHERE building_id=2;

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