且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

mysql删除表并级联删除对表的所有引用

更新时间:2023-02-02 23:12:26

没有单一的命令可以做到这一点.处理此问题的最简单方法是删除约束,然后删除父表.没有约束,你可以***地做到这一点.

There is no single command that can do this. The simplest way to handle this is to drop the constraint and then drop the parent table. Without the constraint, you can do this freely.

ALTER TABLE `user` DROP FOREIGN KEY `USER_FK_sourceYID`;
DROP TABLE `Y`;

删除该列会自动将其从它所属的任何索引中删除.即使它是一个复合索引,它也会留下一个包含其余列的索引.下面是一些假设的示例索引,我们将看到删除列时会发生什么:

Dropping the column automatically removes it from any indexes it belongs to. Even if it's a compound index, it leaves an index with the remaining columns. Here are some hypothetical example indexes, and we'll see what happens when we remove the column:

CREATE INDEX y1 ON `user` (sourceYID);
CREATE INDEX y2 ON `user` (userID, sourceYID);
CREATE INDEX y3 ON `user` (sourceYID, userID);

ALTER TABLE `user` DROP COLUMN `sourceYID`;

结果是索引 y1 消失了,y2y3 都减少为只包含 userID 列的单列索引:

The result is that index y1 is gone, and both y2 and y3 are reduced to single-column indexes containing just the userID column:

SHOW CREATE TABLE `user`\G

CREATE TABLE `user` (
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) NOT NULL,
  `givenName` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`userID`),
  KEY `y2` (`userID`),
  KEY `y3` (`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

因此这两个现在是相同的索引,您应该运行 pt-duplicate-key-checker 分析您的架构以应对此类情况.

Therefore these two are now identical indexes, and you should run pt-duplicate-key-checker to analyze your schema for such cases.