简体   繁体   中英

Adding on Cascade Delete to existing foreign key

I have got a foreign key in one of my tables and wanted to add ON DELETE CASCADE could anyone advise me on how to do it please :) ? thank you

See example :

CREATE TABLE tbl1(
      id INT PRIMARY KEY AUTO_INCREMENT, 
      name INT
    )

    CREATE TABLE tbl2 (
      id INT PRIMARY KEY AUTO_INCREMENT, 
      tbl1_id INT REFERENCES tbl1(id) ON DELETE CASCADE
    )

To add to an existing table :

ALTER TABLE tbl2
   ADD CONSTRAINT tbl1_id_fk
   FOREIGN KEY (tbl1_id)
   REFERENCES tbl1(id)
   ON DELETE CASCADE;

If using InnoDB make sure you have FOREIGN_KEY_CHECKS parameter set to 1
Verify this with the output from SHOW VARIABLES LIKE 'foreign_key_checks' (1=ON, 0=OFF)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM