数据库
首页 > 数据库> > MySQL的乐趣-如何使用IN编写删除语句

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

作者:互联网

当我尝试

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

我懂了

#1093 – You can’t specify target table ‘TreePaths’ for update in FROM clause

如何使删除生效?

更新:
表结构:

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

解决方法:

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

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

标签:sql-delete,sql,mysql
来源: https://codeday.me/bug/20191202/2085673.html