1

我想做在 mysql 中看似简单的删除操作,但遇到了一些麻烦。我想做这个:

delete from table where col_name not in (select distinct col_name from table);

此表没有唯一键。当我尝试这个时,我得到了错误:

您不能在 from 子句中指定更新的目标表;错误编号 1093

mysql社区5.1

有没有办法可以保存此查询的输出->

select distinct col_name from table;

进入温度。表并在删除查询中使用它?

4

2 回答 2

3

您必须使用别名。

delete from table where col_name not in (select a.col_name from (select distinct col_name from table) a);

它应该工作。

编辑:对不起,我误解了这个问题,只关注 SQL 错误。上述请求没有回答删除没有唯一键的重复行的问题。

于 2011-11-10T16:32:22.073 回答
0

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..)
于 2014-02-22T05:11:04.140 回答