我有两张桌子,一张是地板。每个楼层都可以包含房间,这些房间包含位于 Floor 表中的 Floor_ID 的外键。我一直在阅读关于 ON CASCADE DELETE 的文章,这似乎是我的答案,但我对我所读到的内容感到困惑。我知道我可以调用一个包含两个命令的例程,
DELETE FROM Room WHERE Floor_ID = floorID;
DELETE FROM Floor WHERE Floor_ID = floorID;
但是我怎么能使用 ON CASCADE DELETE 来执行同样的事情呢?删除楼层时,与该楼层关联的所有房间也将被删除。
CREATE TABLE `Floor` (
`Floor_ID` int(11) NOT NULL AUTO_INCREMENT,
`Hub_ID` int(11) NOT NULL,
`FloorNum` int(11) NOT NULL,
`FloorName` varchar(45) DEFAULT NULL,
`Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`Hub_ID`,`FloorNum`),
UNIQUE KEY `Floor_ID_UNIQUE` (`Floor_ID`),
KEY `fk_Floor_Hub1_idx` (`Hub_ID`),
CONSTRAINT `fk_Floor_Hub1` FOREIGN KEY (`Hub_ID`) REFERENCES `Hub` (`Hub_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=124 DEFAULT CHARSET=latin1
CREATE TABLE `Room` (
`Room_ID` int(11) NOT NULL AUTO_INCREMENT,
`RoomLabel` varchar(45) NOT NULL,
`Floor_ID` int(11) NOT NULL,
`FloorArea` decimal(10,2) NOT NULL COMMENT 'Square feet',
`RoomHeight` decimal(10,2) DEFAULT NULL COMMENT 'Feet',
`Timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`Room_ID`),
KEY `fk_Room_Floor1_idx` (`Floor_ID`),
CONSTRAINT `fk_Room_Floor1` FOREIGN KEY (`Floor_ID`) REFERENCES `Floor` (`Floor_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=259 DEFAULT CHARSET=latin1