[英]Delete using subselect
I am looking to delete via a subselect. 我想通过子选择删除。 The answers for this question do not solve my issue: MySQL Error 1093 - Can't specify target table for update in FROM clause .
这个问题的答案不能解决我的问题: MySQL错误1093-无法在FROM子句中指定要更新的目标表 。
I found a hackish way to do this and wanted to get feedback on if this was the most optimal solution for doing a DELETE with SUBSELECT
-- 我发现了一种骇人听闻的方法,并且想获得有关这是否是
DELETE with SUBSELECT
进行DELETE with SUBSELECT
最佳解决方案的反馈信息-
DELETE FROM main_history WHERE id NOT IN (
SELECT * from (
SELECT max(id) FROM main_history h GROUP BY instance_id, xpath
) x
)
Basically, I just add in a second (meaningless) subselect to get around the mysql error, which I receive if I just do a normal DELETE with the subselect: 基本上,我只是添加了第二个(无意义的)子选择来解决mysql错误,如果我对子选择执行常规的DELETE操作会收到该错误:
DELETE FROM main_history WHERE id NOT IN (
SELECT max(id) FROM main_history h GROUP BY instance_id, xpath
);
You can't specify target table 'main_history' for update in FROM clause
您无法在FROM子句中指定目标表“ main_history”进行更新
Is this a good solution to the above issue? 这是解决上述问题的好方法吗?
Update: The subselect query performs much better than the join query. 更新:子查询的性能比联接查询好得多。 Here were my findings:
这是我的发现:
# 12m Subselect
DELETE FROM main_history WHERE id NOT IN (
SELECT * from (
SELECT max(id) FROM main_history h GROUP BY instance_id, xpath
) x
)
# 18m Join
Delete m1 from main_history m1 left join
(
SELECT max(id) id FROM main_history h GROUP BY instance_id, xpath
) m2 on m1.id = m2.id
Where m2.id is null;
Right way is using delete join: 正确的方法是使用删除连接:
Delete m1 from main_history m1 left join
(
SELECT max(id) id FROM main_history h GROUP BY instance_id, xpath
) m2 on m1.id = m2.id
Where m2.id is null;
You can use a derived table like this, then MySQL cant see the tablename from the SELECT: 您可以使用这样的派生表,然后MySQL无法从SELECT中看到表名:
DELETE FROM main_history WHERE id NOT IN (
SELECT * FROM (
SELECT * from (SELECT max(id) FROM main_history h
GROUP BY instance_id, xpath) AS x
) AS delrows
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.