mysql delete foreign key

1. Table deletion error
(1) Error description
When deleting a table, the correct syntax DROP TABLE Course; was used, but it could not be deleted, and an error was reported as follows:
[Err] 3730 - Cannot drop table 'course' referenced by a foreign key constraint 'fk_teach_course' on table 'teach'. The main reason is because there are foreign keys.

(2) Solution
Method 1: Turn off the foreign key check and then delete, but don’t forget to turn on the foreign key check after deleting, but I think this method is a bit dangerous. The foreign keys in other tables have not been deleted, so I don’t know what will happen in the future.

SET foreign_key_checks=0; # Turn off foreign key checks
DROP TABLE Course;
SET foreign_key_checks=1; # Turn on foreign key checks

Method 2: Delete all kinds of foreign keys honestly. I really owe it to you when you set up foreign keys when creating a table. Why not set ON UPDATE CASCADE ON DELETE CASCADE by the way

#Syntax: DROP TABLE table_name
#Find the foreign key according to the error message
DROP TABLE Course;
#teach table to delete the foreign key
ALTER TABLE Teach DROP FOREIGN KEY fk_teach_course;
#I delete
DROP TABLE Course;
#I will go, and the score table will be deleted Key
ALTER TABLE Score DROP FOREIGN KEY fk_score_course;
#Again
DROP TABLE Course;
#Finally succeeded

Finally, it is recommended that you use cascading to build tables in the future, so that you will not cry and cry in later maintenance.
————————————————
Copyright statement: This article is an original article of CSDN blogger "Bubling", following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement.
Original link: https://blog.csdn.net/weixin_43762330/article/details/105307195

Guess you like

Origin blog.csdn.net/wangyuhong2267/article/details/125261556