Can't specify target table for update, delete query in mysql
-
26-02-2021 - |
Question
I want to do what seems like a simple delete in mysql but am having some trouble. I want to do this:
delete from table where col_name not in (select distinct col_name from table);
This table does not have a unique key. When I try this, I get the error:
You can't specify target table for update in from clause; ErrorNr. 1093
mysql community 5.1
Is there a way i can save the output from this query ->
select distinct col_name from table;
into temp. table and use it in the delete query?
Solution
You must use an alias.
delete from table where col_name not in (select a.col_name from (select distinct col_name from table) a);
It should work.
Edit : sorry, I misunderstood the question, and only focus on the SQL Error. The probleme to delete duplicate line with no unique key isn't answered by the above request.
OTHER TIPS
the answer by @Molochdaa which is accepted is wrong
Explanation. suppose this is the table
col_name | value
------------------
east | 10
west | 15
east | 10
west | 15
north | 5
east | 10
north | 5
select distinct col_name from table_name gives:
col_name
------------------
east
west
north
now when you write delete from table where col_name not in ( ... )
then no row will be returned as every column is in the returned list
The correct answer would be (suggested by @jeffery_the_wind)
delete from table where col_name in (
select a.col_name from (
select col_name from table group by col_name having count(*)>1
) a
)
Another answer which is more simple
delete from table_name
where rowid not in ( select min(rowid)
from Table_name
group by column1..,column2,...column3..)