in mysql, on delete cascade not working

前端 未结 4 1820
长情又很酷
长情又很酷 2021-01-17 13:04

similar to ON DELETE CASCADE not working in MySQL, but something is not right:

The ANSI Way

-- test delet         


        
相关标签:
4条回答
  • 2021-01-17 13:10

    This happens because the default storage engine 'MyISAM' does not support foreign keys!

    Simply set the engine to InnoDB and make the referencing and referenced columns definition of both tables are matched.

    And this is an example:

    CREATE TABLE `students` (
      `id` INT AUTO_INCREMENT,
      `name` varchar(45) NOT NULL,
      `age` TINYINT NOT NULL,
      PRIMARY KEY(`id`)
    ) ENGINE=InnoDB CHARSET=latin1;
    
    CREATE TABLE `marks` (
      `student_id` INT PRIMARY KEY,
      `mark` DECIMAL(5,2) NOT NULL,
      CONSTRAINT marks_FK_1 FOREIGN KEY(`student_id`) REFERENCES students(`id`) ON DELETE CASCADE
    ) ENGINE=InnoDB CHARSET=latin1;
    
    0 讨论(0)
  • 2021-01-17 13:15

    Set the foreign_key_checks to 1, I ran into this problem while exporting and importing the data during which it was set to 0

    /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=1 */;

    0 讨论(0)
  • 2021-01-17 13:21

    (assuming that should be a "foreign key" not a "primary key" in table t2)

    MySQL simply ignores all inline foreign key constraints without a warning.

    Therefore, you need to explicitly add a foreign key constraint as shown by dnagirl.

    0 讨论(0)
  • 2021-01-17 13:23

    If you create t2 like this it works fine:

    CREATE TABLE  `t2` (
      `id` bigint(20) unsigned NOT NULL,
      `data2` text,
      PRIMARY KEY (`id`),
      CONSTRAINT `FK_t2_1` FOREIGN KEY (`id`) REFERENCES `t1` (`id`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    

    ETA, in answer to concerns about ugly code, the below also works:

    CREATE TABLE  t2 (
      id bigint(20) unsigned NOT NULL PRIMARY KEY,
      data2 text,
      CONSTRAINT  FOREIGN KEY (id) REFERENCES t1(id) ON DELETE CASCADE
    ) ENGINE=InnoDB ;
    

    The main difference is that the data type for t2.id must match that of t1.id and constraints have to be declared after the columns.

    0 讨论(0)
提交回复
热议问题