我想在mysql中做一个简单的删除但是遇到麻烦。我想这样做:
delete from table where col_name not in (select distinct col_name from table);
此表没有唯一键。当我尝试这个时,我得到错误:
您不能在from子句中指定更新的目标表; ErrorNr。 1093
mysql社区5.1
有没有办法可以保存此查询的输出 - >
select distinct col_name from table;
进入临时。表并在删除查询中使用它?
答案 0 :(得分:3)
您必须使用别名。
delete from table where col_name not in (select a.col_name from (select distinct col_name from table) a);
它应该有用。
编辑:抱歉,我误解了这个问题,只关注SQL错误。上述请求无法回答删除没有唯一键的重复行的问题。
答案 1 :(得分:0)
@Molochdaa接受的答案是错误的
解释。 假设这是表
col_name | value
------------------
east | 10
west | 15
east | 10
west | 15
north | 5
east | 10
north | 5
从table_name中选择distinct col_name给出:
col_name
------------------
east
west
north
现在当您编写delete from table where col_name not in ( ... )
时,由于每列都在返回的列表中,因此不会返回任何行
正确的答案是(由@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
)
另一个更简单的答案
delete from table_name
where rowid not in ( select min(rowid)
from Table_name
group by column1..,column2,...column3..)