2012-04-15 126 views
0

我有一個名爲music的數據庫,裏面有4個表格;從數據庫中刪除所有信息(MySQL)

  1. band_members
  2. CDS
  3. 版本。

我想刪除數據庫中與cd005(這是一個cd_id列條目)有關的所有信息。

我想我可以在每一個人的表使用

DELETE FROM table_name WHERE cd_id='cd005' 

,但我想知道是否有通過刪除整個數據庫,在一次有關這個ID的數據來解決這個問題的方法。

回答

1

是的,有一種方法。請檢查mysql文檔以查找外鍵級聯刪除。

例子:

CREATE TABLE parent (id INT NOT NULL, 
        PRIMARY KEY (id) 
) ENGINE=INNODB; 
CREATE TABLE child (id INT, parent_id INT, 
        INDEX par_ind (parent_id), 
        FOREIGN KEY (parent_id) REFERENCES parent(id) 
         ON DELETE CASCADE 
) ENGINE=INNODB; 

Insert into parent set id=1; 
Insert into parent set id=2; 
Insert into parent set id=3; 
Insert into child set id=1, parent_id=1; 
Insert into child set id=2, parent_id=1; 


select * from parent; 
select * from child; 
delete from parent where id=1; 
select * from parent; 
select * from child; 


ID 
1 
2 
3 
Record Count: 3; Execution Time: 0ms View Execution Plan 
ID PARENT_ID 
1 1 
2 1 
Record Count: 2; Execution Time: 0ms View Execution Plan 
Record Count: 0; Execution Time: 1ms 
ID 
2 
3 
Record Count: 2; Execution Time: 0ms View Execution Plan 
Record Count: 0; Execution Time: 0ms 
+0

我會級聯 – sikas 2012-04-15 19:07:30

+0

去如何使用級聯刪除?我可以從我的表中看到,我的cd_id是我的cds表中的主鍵。我想如果我刪除它,所有的子項也應該刪除? – 2012-04-15 19:11:49