gpt4 book ai didi

MySQL InnoDB 在删除级联时更改引用操作

转载 作者:行者123 更新时间:2023-11-29 02:30:50 29 4
gpt4 key购买 nike

有没有比删除和添加约束更快的方法向现有外键添加 CASCADE 规则?

SET foreign_key_checks = 0;
ALTER TABLE drop foreign key ...;
ALTER TABLE add foreign key ...;
SET foreign_key_checks = 1;

手册说,您不能在单个 ALTER TABLE 语句的单独子句中添加外键和删除外键。您必须使用单独的语句。

最佳答案

我尝试使用“MySQL Workbench 5.2 CE->EER Diagram”仅更改外键选项:从表中的“on delete restrict”到“on delete cascade”:

CREATE  TABLE IF NOT EXISTS `mydb`.`Customers` (
`CustomerID` INT NOT NULL AUTO_INCREMENT ,
`FirstName` VARCHAR(45) NOT NULL ,
`LastName` VARCHAR(45) NOT NULL ,
`Email` VARCHAR(500) NOT NULL ,
`Password` VARCHAR(500) NOT NULL ,
`AddressID` INT NULL ,
PRIMARY KEY (`CustomerID`) ,
INDEX `AddressID_idx` (`AddressID` ASC) ,
UNIQUE INDEX `Email_UNIQUE` (`Email` ASC) ,
CONSTRAINT `CustomerAddressID`
FOREIGN KEY (`AddressID` )
REFERENCES `mydb`.`Address` (`AddressID` )
ON DELETE RESTRICT
ON UPDATE CASCADE)
ENGINE = InnoDB;

因此,该 GUI 工具生成以下代码:

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

ALTER TABLE `mydb`.`Customers` DROP FOREIGN KEY `CustomerAddressID` ;

ALTER TABLE `mydb`.`Customers`
ADD CONSTRAINT `CustomerAddressID`
FOREIGN KEY (`AddressID` )
REFERENCES `mydb`.`Address` (`AddressID` )
ON DELETE CASCADE
ON UPDATE CASCADE;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

我认为这意味着它是分两步更改外键选项的自然方式。

关于MySQL InnoDB 在删除级联时更改引用操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13414273/

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