MySQL foreign key constraints, cascade delete

前端 未结 3 497
一个人的身影
一个人的身影 2020-11-22 06:19

I want to use foreign keys to keep the integrity and avoid orphans (I already use innoDB).

How do I make a SQL statment that DELETE ON CASCADE?

If I delete a

3条回答
  •  盖世英雄少女心
    2020-11-22 06:59

    I got confused by the answer to this question, so I created a test case in MySQL, hope this helps

    -- Schema
    CREATE TABLE T1 (
        `ID` int not null auto_increment,
        `Label` varchar(50),
        primary key (`ID`)
    );
    
    CREATE TABLE T2 (
        `ID` int not null auto_increment,
        `Label` varchar(50),
        primary key (`ID`)
    );
    
    CREATE TABLE TT (
        `IDT1` int not null,
        `IDT2` int not null,
        primary key (`IDT1`,`IDT2`)
    );
    
    ALTER TABLE `TT`
        ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
        ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;
    
    -- Data
    INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
    INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
    INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
    (1,1),(1,2),(1,3),(1,4),
    (2,1),(2,2),(2,3),(2,4),
    (3,1),(3,2),(3,3),(3,4),
    (4,1),(4,2),(4,3),(4,4);
    
    -- Delete
    DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
    TRUNCATE `T2`; -- Can't truncate a table with a referenced field
    DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1
    

提交回复
热议问题