简体   繁体   中英

Mysql on delete cascade not working

i have the tables:

DROP TABLE IF EXISTS `files`;
CREATE TABLE IF NOT EXISTS `files` (
  `id` VARCHAR(36)  NOT NULL,
  `name` VARCHAR(50) NOT NULL,
  `extension` VARCHAR(5) NOT NULL,
  `version` INT(11) NOT NULL,
  `date` DATE NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

and TagsFiles:

DROP TABLE If EXISTS  `tags_files`;
CREATE TABLE IF NOT EXISTS `tags_files` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `tag_id` INT(11) NOT NULL,
  `file_id` VARCHAR(36) NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT FOREIGN KEY (`file_id`) REFERENCES `files` (`id`) ON DELETE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

if i now delete one or more entries of the tags_files table, there are no entries in files deleted. Can someone tell me why?

The constrain you have now will delete from tags_files when a referenced id will be deleted on files .

If you need to automatically delete from files when you delete from tags_files , then the constrain must be on files table.

Like this:

DROP TABLE IF EXISTS `files`;
CREATE TABLE IF NOT EXISTS `files` (
    `id` VARCHAR(36)  NOT NULL,
    `name` VARCHAR(50) NOT NULL,
    `extension` VARCHAR(5) NOT NULL,
    `version` INT(11) NOT NULL,
    `date` DATE NOT NULL,
    PRIMARY KEY (`id`),
    CONSTRAINT FOREIGN KEY (`id`) REFERENCES `tags_files` (`file_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and TagsFiles:

DROP TABLE If EXISTS  `tags_files`;
CREATE TABLE IF NOT EXISTS `tags_files` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `tag_id` INT(11) NOT NULL,
    `file_id` VARCHAR(36) NOT NULL,
    PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

Well you get an error in above example because MySQL don't allow constraints for varchar type. If you change it to char you can. But you also need to change the sequence of the execution queries due to constrains. Do like this:

DROP TABLE IF EXISTS `files`;
DROP TABLE If EXISTS  `tags_files`;

CREATE TABLE IF NOT EXISTS `tags_files` (
    `id` INT(11) NOT NULL,
    `tag_id` INT(11) NOT NULL,
    `file_id` char(36) NOT NULL,
    PRIMARY KEY (`file_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `files` (
    `id` char(36)  NOT NULL,
    `name` VARCHAR(50) NOT NULL,
    `extension` VARCHAR(5) NOT NULL,
    `version` INT(11) NOT NULL,
    `date` DATE NOT NULL,
    PRIMARY KEY (`id`),
    CONSTRAINT FOREIGN KEY (`id`) REFERENCES `tags_files` (`file_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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