级联不起作用

时间:2014-02-06 04:51:16

标签: mysql sql cascading-deletes

我有几个弱连接的表,当我从主表中删除时,我希望删除它们两个。

表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
);

但是当我从Car表中删除一辆汽车时,它不会从Tags表中删除。我甚至尝试在创建表之后添加约束,但得到相同的结果。

1 个答案:

答案 0 :(得分: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;