是否有更快的方法将CASCADE规则添加到现有外键而不是删除和添加约束?
SET foreign_key_checks = 0;
ALTER TABLE drop foreign key ...;
ALTER TABLE add foreign key ...;
SET foreign_key_checks = 1;
手动说,您不能在单个ALTER TABLE语句的单独子句中添加外键并删除外键。您必须使用单独的声明。
答案 0 :(得分:2)
我尝试使用'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;
我认为这意味着通过两个步骤更改外键选项的自然方式。