MySQL DELETE FROM与子查询作为条件

我正在尝试这样一个查询:

DELETE FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN (
    SELECT DISTINCT(th1.tid)
    FROM term_hierarchy AS th1
    INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
    WHERE th1.parent = 1015
);

你可以告诉我,如果相同的tid有其他父母,我想删除父关系1015。但是,这会给我一个语法错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS th
WHERE th.parent = 1015 AND th.tid IN (
  SELECT DISTINCT(th1.tid)
  FROM ter' at line 1

我已经检查了文档,并自己运行子查询,这一切似乎都要检查出来。任何人都可以弄清楚这里有什么问题吗?

更新:如下回答,MySQL不允许在子查询中使用要删除的表。

最佳解决方案

您不能指定删除的目标表。

解决方法

create table term_hierarchy_backup (tid int(10)); <- check data type

insert into term_hierarchy_backup 
SELECT DISTINCT(th1.tid)
FROM term_hierarchy AS th1
INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
WHERE th1.parent = 1015;

DELETE FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN (select tid from term_hierarchy_backup);

次佳解决方案

对于那些在使用子查询时想要删除这个问题的人来说,我给你这个例子说明了MySQL的优势(即使有些人似乎认为不能完成):

DELETE e.*
FROM tableE e
WHERE id IN (SELECT id
             FROM tableE
             WHERE arg = 1 AND foo = 'bar');

会给你一个错误:

ERROR 1093 (HY000): You can't specify target table 'e' for update in FROM clause

但是这个查询:

DELETE e.*
FROM tableE e
WHERE id IN (SELECT id
             FROM (SELECT id
                   FROM tableE
                   WHERE arg = 1 AND foo = 'bar') x);

将工作很好:

Query OK, 1 row affected (3.91 sec)

将子查询包含在一个附加的子查询(这里叫做x)中,MySQL将会很高兴地做你所要求的。

第三种解决方案

DELETE关键字后应该包含别名:

DELETE th
FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN 
(
    SELECT DISTINCT(th1.tid)
    FROM term_hierarchy AS th1
    INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
    WHERE th1.parent = 1015
);

第四种方案

您需要在delete语句中再次引用别名,如:

DELETE th FROM term_hierarchy AS th
....

As outlined here in MySQL docs.

第五种方案

我以一种略微不同的方式接近这个,对我来说是有效的;

我需要从引用conditions表的表中删除secure_links,其中不再有任何条件行。一个家务脚本基本上这给了我错误 – 您不能指定删除的目标表。

所以在这里寻找灵感,我想出了下面的查询,它的工作正常。这是因为它创建了一个用作DELETE参考的临时表sl1

DELETE FROM `secure_links` WHERE `secure_links`.`link_id` IN 
            (
            SELECT
                `sl1`.`link_id` 
            FROM 
                (
                SELECT 

                    `sl2`.`link_id` 

                FROM 
                    `secure_links` AS `sl2` 
                    LEFT JOIN `conditions` ON `conditions`.`job` = `sl2`.`job` 

                WHERE 

                    `sl2`.`action` = 'something' AND 
                    `conditions`.`ref` IS NULL 
                ) AS `sl1`
            )

为我工作

参考文献

  • MySQL DELETE FROM with subquery as condition

你可能感兴趣的:(java知识)