2011-11-19 52 views
3

當我嘗試樂趣與MySQL - 如何寫有一個delete語句

DELETE FROM `TreePaths` WHERE `descendant` IN (SELECT `descendant` FROM `TreePaths` WHERE `ancestor`= 0x04); 

我得到

#1093 - 您不能指定目標表「的TreePaths」的更新中FROM子句

我怎樣才能讓刪除工作?

更新: 表結構:

CREATE TABLE TreePaths (
    ancestor  VARBINARY(16) NOT NULL, 
    descendant  VARBINARY(16) NOT NULL, 
    PRIMARY KEY (`ancestor`, `descendant`), 
    FOREIGN KEY (`ancestor`) REFERENCES Library(iD), 
    FOREIGN KEY (`descendant`) REFERENCES Library(iD) 
); 

表數據:

ancestor descendant 
     01 01 
     02 02 
     02 03 
     03 03 
     02 04 
     04 04 
     02 05 
     04 05 
     05 05 
     02 06 
     04 06 
     06 06 
     07 07 
     08 08 
     09 09 
     10 10 
+0

顯示你的表'structure'和'數據'。 – diEcho

+0

我猜想它同樣的問題 http://stackoverflow.com/questions/45494/sql-delete-cant-specify-target-table-for-update-in-from-clause – Zohaib

+1

閱讀這一個:HTTP ://dev.mysql.com/doc/refman/5.0/en/subquery-restrictions.html – diEcho

回答

3

在MySQL更容易做多表中刪除:

DELETE paths_to_subtree FROM `TreePaths` AS paths_to_subtree 
JOIN `TreePaths` AS subtree USING (`descendant`) 
WHERE subtree.`ancestor`= 0x04; 
+0

謝謝。 MySQL似乎讓所有事情都變得比它需要的更難一些: -/ – Justin808

+0

同樣感謝大家的關注http://www.slideshare.net/billkarwin/models-for-hierarchical-data – Justin808

0

你可以創建一個臨時表來存儲後代:

CREATE TEMPORARY TABLE tmpTable (descendants VARBINARY(16) NOT NULL); 
INSERT INTO tmpTable(descendants) (SELECT descendant FROM TreePaths WHERE ancestor = 0x04); 
DELETE FROM TreePaths WHERE descendant IN (SELECT descendant from tmpTable); 
DROP TABLE tmpTable; 

最後一行是可選的,如果你想要做別的事情之前,釋放內存可以使用 - 臨時表在會話結束DROP掉