简体   繁体   中英

mysql ON DELETE CASCADE

network table

"CREATE TABLE network("
 . "n_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,"
 . "nname VARCHAR(50) NOT NULL,"
 . "ndate DATE NOT NULL"
 . ");";

locality table

"CREATE TABLE locality("
 ."l_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,"
 ."lname varchar(50) NOT NULL,"
 ."ldate varchar(50) NOT NULL,"
 ."n_id int NOT NULL,"
 . "CONSTRAINT locality_fk_1 FOREIGN KEY (n_id) REFERENCES network(n_id)ON DELETE CASCADE ON UPDATE CASCADE"
 . ");"; 

Added from comments :

It gives me an following error:

Network not deletedCannot delete or update a parent row: a foreign key constraint fails (accelore.locality, CONSTRAINT locality_ibfk_1 FOREIGN KEY (n_id) REFERENCES network (n_id))

You have added a foreign key constraint so it'll not get deleted directly,you have to drop the constraint first.
alter table locality drop constraint locality_ibfk_1 will drop the constraint and you can delete network OR
If you just want to delete data from both the table, use:

delete from network where n_id = n_id; 

will delete all data in both the table without dropping any of the table. Or
If you use specific n_id it'll delete that particular data in both the tables.

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