Question

Is there a faster way to add a CASCADE rule to an existing foreign key than dropping and adding the constraint?

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

Manual says, you cannot add a foreign key and drop a foreign key in separate clauses of a single ALTER TABLE statement. You must use separate statements.

Was it helpful?

Solution

I tried to use 'MySQL Workbench 5.2 CE->EER Diagram' to change only the foreign key option: from 'on delete restrict' to 'on delete cascade' in the table:

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;

So, that GUI tool generate the following code:

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;

I think it means that it's the natural way to change the foreign key option by two steps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top