2017-02-20 62 views
0

刪除數據我有3個表MySQL的 - 如何從整個相關表

tbl_car 
id | name 
1 | toyota 

tbl_brand 
id | brand_name | **car_id** (one to many) 
1 | brand1 | 1 
2 | brand2 | 1 


tbl_item 
id | item_name | **brand_id** (one to many) 
1 | brand1_item1 | 1 
2 | brand1_item2 | 1 
3 | brand2_item1 | 2 
4 | brand2_item2 | 2 

我想從tbl_car刪除數據ID = 1,我嘗試

DELETE tbl_car a LEFT JOIN tbl_brand b ON a.id = b.car_id LEFT JOIN tbl_item c ON b.id = c.brand_id WHERE a.id = 1

但它沒有工作。我想要的是刪除tbl_car id = 1和關係表中的全部數據.i感謝任何幫助,謝謝。

+1

看後進入on刪除外鍵 – Mihai

+0

我使用CASCADE選項那個,但是我讀了那麼多文章告訴說ON DELETE CASCADE是個壞主意。像這樣http://dba.stackexchange.com/questions/74627/difference-between-on-delete-cascade-on-update-cascade-in-mysql – plonknimbuzz

+1

@plonknimbuzz不使用級聯的原因與不使用級聯相同在一個語句中使用多表刪除。 –

回答

0

你可以試試這樣:

DELETE a.*,b.*,c.* FROM tbl_car a LEFT JOIN tbl_brand b ON a.id = b.car_id LEFT JOIN tbl_item c ON b.id = c.brand_id WHERE a.id = 1 

,或者嘗試使用觸發器表中刪除tbl_car

delimiter $$ 
    CREATE TRIGGER `after_delete_Car`  
     AFTER DELETE ON `tbl_car`  
     FOR EACH ROW  
    BEGIN 
     DELETE FROM tbl_brand WHERE car_id=OLD.id; 
     DELETE FROM tbl_item WHERE brand_id=OLD.id; 
    END 
    $$ 
    delimiter ; 
+1

觸發器是正確的做法。但我更喜歡刪除級聯。謝謝你danilo你的時間和答案 – plonknimbuzz