gpt4 book ai didi

MySQL 删除级联

转载 作者:行者123 更新时间:2023-11-29 04:53:44 24 4
gpt4 key购买 nike

我想知道是否有人可以帮助我。

我想使用“删除级联”mySQL 功能,以便当从“用户详细信息”表中删除用户时,它会从我的数据库中的其他表中删除他们的记录。

阅读 Stackoverflow 上的一些帖子以及我在 Internet 上进行的研究后,我将我的表更改为 InnoDB 并开始更改我现有的表。

我已经能够将“使用外键删除级联”添加到我的第一个表中,但是当我尝试对任何其他表执行相同操作时,我收到以下错误:

#1005 - Can't create table './db369054642/#sql-30d_bd1a57.frm' (errno: 121)

但我不确定为什么会收到此错误,因为我更改的第一个表工作顺利。

谁能告诉我,你们只能将父表链接到一个子表吗?

父表(用户详细信息)

DROP TABLE IF EXISTS `userdetails`;
CREATE TABLE IF NOT EXISTS `userdetails` (
`userid` int(6) NOT NULL auto_increment,
`forename` varchar(20) NOT NULL,
`surname` varchar(30) NOT NULL,
`emailaddress` varchar(150) NOT NULL,
`password` varchar(200) NOT NULL,
`passwordhint` varchar(20) NOT NULL,
`subscriptionexpiration` date NOT NULL,
`salt` varchar(200) NOT NULL,
PRIMARY KEY (`userid`),
UNIQUE KEY `emailaddress` (`emailaddress`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

子表(检测器)

DROP TABLE IF EXISTS `detectors`;
CREATE TABLE IF NOT EXISTS `detectors` (
`userid` int(6) NOT NULL,
`detectorid` int(6) NOT NULL auto_increment,
`detectorname` varchar(30) NOT NULL,
PRIMARY KEY (`detectorid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 PACK_KEYS=0 AUTO_INCREMENT=1 ;

删除级联SQL语句

ALTER TABLE detectors
add CONSTRAINT fk_userdetails
FOREIGN KEY (userid)
REFERENCES userdetails(userid)
ON DELETE CASCADE

最佳答案

您的表和引用表是否在涉及的列上都有索引

来自 http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html :

InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. (This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index_name, if given, is used as described previously.

首先尝试创建必要的索引,或者向我们展示 SHOW CREATE TABLE yourTableName 的输出,以便我们检查索引是否存在并且没有名称冲突。

关于MySQL 删除级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com