mysql 關聯刪除 mysql如何刪除關聯表

2021-10-25 14:24:53 字數 944 閱讀 9215

mysql資料庫中,表與表之間進行關聯之後,就不可隨意的進行刪除操作,否則會影響所有關聯表之間的結構,那麼如何安全的刪除關聯表呢,讓我們來了解一下。

mysql使用drop命令刪除關聯表,方法為:

1. 刪除表的外來鍵約束

外來鍵是乙個特殊字段,其將某乙個表與其父表建立關聯關係。在建立表的時候,外來鍵約束就已經設定好了。去掉他們之間的關聯關係需要用到下面語句。alter table 表名 drop foreign key 外來鍵別名;

外來鍵別名引數指建立表時設定的外來鍵代號。

2. 刪除沒有被關聯的普通表drop table 表名;

刪除乙個表時,表中的所有資料也會被刪除。刪除表時最好先將表中的資料備份一下。

3. 刪除被其他表關聯的父表

當刪除有關聯關係的表時,用drop table example1 會報錯,原因是有外來鍵依賴於該錶

例如建立了乙個example4表依賴於example1表,example4表的外來鍵stu_id依賴於example1表的主鍵。example1表時example4表的父表。

如果要刪除example4表,必須先去掉這種依賴關係。最簡單的辦法是先刪除子表example4,然後刪除父表example1。但這樣可能會影響子表的其他資料。

另一種方法是先刪除子表的外來鍵約束,然後刪除父表。這種方法不會影響子表的其他資料,可以保證資料庫的安全。

比如,example4表的外來鍵別名是d_fk,刪除example4的外來鍵約束

alter table example4 drop foreign key d_fk;。

可以通過show create table example4 \g來檢視是否已刪除。

然後再執行drop table example1;.

執行成功則表示操作成功。

mysql 多表關聯刪除

兩張表關聯刪除 delete a,b from table1 a inner join table2 b on a.id b.aid where a.id 1 或者也可以 delete a,b from table1 a,table2 b where a.id b.aid and a.id 1 三張...

mysql 多表關聯刪除

sql檔案 set foreign key checks 0 table structure for stu tea drop table ifexists stu tea create table stu tea stu id int 11 not null,tea id int 11 not n...

MySQL刪除關聯表的資料

刪除班級以及班級下的所有學生 由於grade表和student表之間具有關聯關係,參照列被參照的值,是不能被刪除的,因此,在刪除軟體一班時,一定要先刪除班級的所有學生,然後,再刪除班級 在student表中,刪除軟體一班的所有學生 在grade表中,將軟體一班刪除 如果直接刪除班級,會報錯 因此,在...