2013-04-03 59 views
0

創建觸發器成功MySQL的觸發器不能援引

mysqli_query($this->conn, 
    "CREATE TRIGGER `before_delete_address` 
    BEFORE DELETE ON address FOR EACH ROW 
    DELETE FROM city WHERE cityid = OLD.cityid"); 

但是當我執行以下查詢

DELETE FROM address WHERE addressid = 18 

Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`gamecomp`.`address`, CONSTRAINT `cityid` FOREIGN KEY (`cityid`) REFERENCES `city` (`cityid`) ON UPDATE CASCADE) 0.039 sec 

約束上輸出下列錯誤代碼地址表設置爲On Update cascadeOn Delete restrict

地址表的列addressid, address, cityid, zipcode,cityid是一個FK參照城市表包含cityid, city, countryid

有人能指出我做了什麼錯?感謝

回答

0

,而不是之前刪除的城市使用後刪除地址

+0

它給了我之前同樣的錯誤 – jctank

+0

insted的後添加 – shola

+0

你有沒有試過以上? – shola

2

address FOREIGN KEY (cityid) REFERENCES city (cityid) ON DELETE RESTRICT意味着你不能刪除一個城市,任何address.cityid引用。由於這正是你的觸發器所做的,你會得到一個外鍵約束錯誤。

即使您將此觸發器設爲AFTER DELETE ON,您仍可能有其他地址行引用城市,這意味着您仍可能會收到外鍵約束錯誤。您還應該驗證city表上沒有觸發器,這可能會破壞address中外鍵的約束。

在刪除相應的city之前,您需要首先驗證對cityid的所有引用都已刪除。坦率地說,我不相信你甚至應該試圖做到這一點。在設計良好的模式中,一些孤兒記錄不應該成爲問題。如果他們真的麻煩你,他們可以用cronjob定期刪除而不是用觸發器刪除。

如果你堅持一個觸發器,試試這個:

CREATE TRIGGER `delete_city_orphans` 
AFTER DELETE ON address FOR EACH ROW 
DELETE FROM city WHERE city.id=OLD.cityid 
    AND NOT EXISTS (SELECT * FROM address WHERE cityid=OLD.cityid) 
+0

謝謝,我會試試看 – jctank