Practical Operation Method of mysql Deleting Association Table

  • 2021-12-04 11:36:16
  • OfStack

In mysql database, after the association between tables, you can't delete them at will, otherwise it will affect the structure between all associated tables, so how to delete the associated tables safely, let's understand 1.

Delete a foreign key constraint for a table

A foreign key is a special field that associates a table with its parent table. When the table is created, the foreign key constraint is already set. Removing the relationship between them requires the following statement.


alter table  Table name  drop foreign key  Foreign key alias; 

The foreign key alias parameter refers to the foreign key code set when the table is created.

2. Delete normal tables that are not associated


drop table  Table name; 

When you delete a table, all the data in the table will also be deleted. When deleting a table, it is best to back up the data in the table first.

3. Delete parent tables associated with other tables

An error is reported with drop table example1 when deleting an associated table because a foreign key depends on the table

For example, an example4 table is created that depends on the example1 table, and the foreign key stu_id of the example4 table depends on the primary key of the example1 table. The example1 table is the parent of the example4 table.

If you want to delete the example4 table, you must first remove this dependency. The easiest way is to delete the child table example4 first, and then delete the parent table example1. However, this may affect other data of child tables.

Another method is to delete the foreign key constraint of the child table first, and then delete the parent table. This method will not affect other data of child tables, and can ensure the security of the database.

For example, the foreign key alias of the example4 table is d_fk, and the foreign key constraint of example4 is deleted

alter table example4 drop foreign key d_fk; .

You can check whether it has been deleted through show create table example4\ G.

Then execute drop table example1; .

Successful execution means successful operation.


Related articles: