我有预订表和订单表。每个预订都是订单的一部分,因此将intOrderID存储为外键。我有以下MySQL程序
CREATE PROCEDURE `usp_archive` (
IN p_dtmBefore DATE
)
BEGIN
START TRANSACTION;
INSERT INTO tblArchivedOrders SELECT * FROM tblOrders O WHERE (SELECT MAX(dtmDateTime) FROM tblBookings WHERE intOrderID = O.intOrderID) < p_dtmBefore;
INSERT INTO tblArchivedBookings SELECT * FROM tblBookings WHERE intOrderID IN (SELECT intOrderID FROM tblArchivedOrders);
DELETE FROM tblBookings WHERE intOrderID IN (SELECT intOrderID FROM tblArchivedOrders);
DELETE FROM tblOrders WHERE intOrderID IN (SELECT intOrderID FROM tblArchivedOrders);
COMMIT;
END $$
DELIMITER ;
失败并显示以下消息
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`mjlprodu_CGUA_test`.`tblBookings`, CONSTRAINT `tblBookings_ibfk_2` FOREIGN KEY (`intOrderID`) REFERENCES `tblOrders` (`intOrderID`))
我看到这条消息说tblBookings中仍然有一个预订,它引用了我试图删除的tblOrders中的订单,因此我无法删除该订单。但是,如果我运行此查询
SELECT * FROM tblOrders WHERE intOrderID IN (SELECT intOrderID FROM tblArchivedOrders) AND intOrderID IN (SELECT intOrderID FROM tblBookings)
它不返回任何行。
所以我已经注释掉了“DELETE FROM tblOrders ..”这一行,程序运行正常。然后我自己运行“DELETE FROM tblOrders ..”行,这也运行正常!
这究竟是怎么发生的?