MySQL绕过错误1093

时间:2010-12-19 19:53:51

标签: mysql sql sql-update sql-delete mysql-error-1093

错误1093指出如果子查询查询要删除的表,则无法使用子查询更新或删除。

所以你做不到

delete from table1 where id in (select something from table1 where condition) ;

好的,解决这个限制的最佳方法是什么(假设您确实需要子查询来执行删除,并且无法完全消除自引用子查询?)

编辑:

以下是对有兴趣的人的查询:

mysql> desc adjacencies ;
+---------+---------+------+-----+---------+-------+
| Field   | Type    | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| parent  | int(11) | NO   | PRI | NULL    |       |
| child   | int(11) | NO   | PRI | NULL    |       |
| pathLen | int(11) | NO   |     | NULL    |       |
+---------+---------+------+-----+---------+-------+



-- The query is going to
-- tell all my children to
-- stop thinking my old parents
-- are still their parents

delete from adjacencies
where parent in 
(
-- ALL MY PARENTS,grandparents
  select parent
  from adjacencies
  where child=@me
  and parent!=@me
)

-- only concerns the relations of my
-- grandparents WHERE MY CHILDREN ARE CONCERNED
and child in
(
  -- get all my children
  select child
  from adjacencies
  where parent=@me
)

;

所以我到目前为止所尝试的是创建一个名为adjsToDelete

的临时表
create temporary table adjsToRemove( parent int, child int ) ;
insert into adjsToRemove...

所以现在我有一个要删除的关系集合,其中父/子对各自唯一地标识要删除的行。但如何从邻接表中删除每个

我似乎需要为auto_increment中的每个条目添加一个唯一的adjacencies ed键,是吗?

5 个答案:

答案 0 :(得分:7)

http://bugs.mysql.com/bug.php?id=6980中找到的解决方法对我有用,就是为将返回项目的子查询创建一个别名。所以

delete from table1 where id in 
  (select something from table1 where condition)

将更改为

delete from table1 where id in
  (select p.id from (select something from table1 where condition) as p)

答案 1 :(得分:2)

你可以做到

delete t1,t2 
FROM  table1 t1  
INNER JOIN 
table1 t2 ON (t2.something = t1.id);

对于问题中的查询,这应该是等效的:

delete A
from adjacencies A
join adjacencies B ON A.parent = B.parent AND B.child=@me AND B.parent != @me
join adjacencies C ON A.child = C.child AND C.parent=@me

答案 2 :(得分:1)

Currently, you cannot delete from a table and select from the same table in a subquery - details

您无法无法指定要删除的目标表

我的一个解决方法:MySQL DELETE FROM with subquery as condition

答案 3 :(得分:1)

简化为:

-- Collect ids
CREATE TEMPORARY TABLE cleanup_lookup AS 
SELECT id FROM table1 WHERE condition;

-- Delete the selected records
DELETE t FROM table1 t INNER JOIN cleanup_lookup l ON t.id = l.id;

-- Temporary tables get dropped when the connection is closed.

答案 4 :(得分:0)

你可以毫不犹豫地使用这个。

您的查询:

delete from table1 
where id in (select something from table1 where condition);

更新了查询:

DELETE FROM table1 
WHERE id IN (SELECT * 
             FROM 
                 (SELECT MIN(id) FROM table1 GROUP BY Column2) x);

此处Column2是您要查找重复记录的列。