我有兩張桌子,一張是Floor。每個樓層可以包含房間,其中包含位於Floor表中的Floor_ID的外鍵。我一直在閱讀關於CASCADE DELETE,這似乎是我的答案,但我對我讀過的內容感到困惑。我知道我可以調用包含兩個命令的例程,但我怎麼能使用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
這可能會有所幫助:http://stackoverflow.com/questions/511361/how-do-i-use-on-delete-cascade-in-mysql – sgeddes
我以爲它是這樣工作的,但並不完全當然。我會嘗試它,我猜,並希望最好的。 –