Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

php - ON DELETE CASCADE not working in MySQL

I am using the following SQL to create a table named app_info:

CREATE TABLE IF NOT EXISTS `app_info` (
`_id` int(11) NOT NULL AUTO_INCREMENT,
`app_name` varchar(50) DEFAULT NULL,
`app_owner` varchar(50) DEFAULT NULL,
`last_update` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

I am using the following SQL to create a table named tab_info:

CREATE  TABLE `myDB`.`tab_info` (
`_id` INT NOT NULL AUTO_INCREMENT ,
`app_id` INT NOT NULL ,
`tab_title` VARCHAR(15) NOT NULL ,
PRIMARY KEY (`_id`) ,
UNIQUE INDEX `app_id_UNIQUE` (`app_id` ASC) ,
INDEX `app_tab_key` (`app_id` ASC) ,
CONSTRAINT `app_tab_key`
  FOREIGN KEY (`app_id` )
  REFERENCES `myDB`.`app_info` (`_id` )
  ON DELETE CASCADE
  ON UPDATE CASCADE); 

But when I delete data from primary key table, the orphaned rows in the foreign key table are not being deleted automatically. Does anyone know what the problem could be?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The MyISAM storage engine doesn't support foreign key constraints. The constraint is parsed but silently ignored.

To fix your problem use the InnoDB engine instead (for both tables).

CREATE TABLE ( ... ) ENGINE = InnoDB ... ;

Instead of dropping your tables and recreating them you can also change the storage engine:

ALTER TABLE myDB.app_info ENGINE = InnoDB;
ALTER TABLE myDB.tab_info ENGINE = InnoDB;

After changing the engine you will need to add the foreign key constraint again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...