2014-02-06 73 views
0

我有一對弱連接的表,我希望在從主表中刪除時刪除可以在兩者之間工作。級聯不起作用

表1:

CREATE TABLE Car(
cID INTEGER, 
color VARCHAR(10), 
primary key (cID) 
); 

CREATE TABLE Tags(
tID INTEGER, 
expDate VARCHAR(10), 
cID INTEGER, 
primary key (tID, cID), 
foreign key (cID) references Car(cID) on delete cascade 
); 

但是,當我從車表中刪除了一輛車,它不會從標籤表中刪除。我甚至嘗試在創建表後添加約束,但得到相同的結果。

+0

它的工作在我的MySQL罰款,請再次檢查.. – jainvikram444

+0

@vikramjain我又試了一次,同樣的結果,我試過如下:'DELETE FROM車廂,CID = 1',它成功地工作了車表,但是當我檢查標籤表時,它仍然存在。 – ZAX

回答

0
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 
SET time_zone = "+00:00"; 


-- -------------------------------------------------------- 

-- 
-- Table structure for table `Car` 
-- 

CREATE TABLE IF NOT EXISTS `Car` (
    `cID` int(11) NOT NULL AUTO_INCREMENT, 
    `color` varchar(10) DEFAULT NULL, 
    PRIMARY KEY (`cID`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; 

-- 
-- Dumping data for table `Car` 
-- 

INSERT INTO `Car` (`cID`, `color`) VALUES 
(2, 'B'), 
(4, 'A'); 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `Tags` 
-- 

CREATE TABLE IF NOT EXISTS `Tags` (
    `tID` int(11) NOT NULL AUTO_INCREMENT, 
    `expDate` varchar(10) DEFAULT NULL, 
    `cID` int(11) NOT NULL DEFAULT '0', 
    PRIMARY KEY (`tID`,`cID`), 
    KEY `cID` (`cID`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; 

-- 
-- Dumping data for table `Tags` 
-- 

INSERT INTO `Tags` (`tID`, `expDate`, `cID`) VALUES 
(3, 'AA', 2), 
(4, 'BB', 2), 
(5, '11', 4), 
(6, '22', 4); 

-- 
-- Constraints for dumped tables 
-- 

-- 
-- Constraints for table `Tags` 
-- 
ALTER TABLE `Tags` 
    ADD CONSTRAINT `Tags_ibfk_1` FOREIGN KEY (`cID`) REFERENCES `Car` (`cID`) ON DELETE CASCADE; 

- 現在您將刪除一條記錄;

--DELETE FROM Car WHERE cID=4;