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.
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 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:
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
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;