有趣的MySQL - 如何使用IN编写删除语句

时间:2011-11-19 02:08:31

标签: mysql sql sql-delete

当我尝试

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

我得到了

  

#1093 - 您无法在FROM子句

中指定目标表'TreePaths'以进行更新

如何让删除工作?

更新 表结构:

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

2 个答案:

答案 0 :(得分:3)

在MySQL中,更容易进行多表删除:

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

答案 1 :(得分: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;

最后一行是可选的,如果你想在制作其他内容之前释放内存,可以使用它 - 临时表在会话结束时被删除