有没有比删除和添加约束更快的方法将 CASCADE 规则添加到现有外键?
SET foreign_key_checks = 0;
ALTER TABLE drop foreign key ...;
ALTER TABLE add foreign key ...;
SET foreign_key_checks = 1;
手册说,您不能在单个 ALTER TABLE 语句的单独子句中添加外键和删除外键。您必须使用单独的语句。
有没有比删除和添加约束更快的方法将 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;
我认为这意味着通过两步更改外键选项是自然的方式。