【问题标题】:Can't specify target table for update, delete query in mysql无法在mysql中指定更新、删除查询的目标表
【发布时间】:2011-12-26 08:10:04
【问题描述】:

我想在 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;

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

【问题讨论】:

  • 是否要删除重复项。正确的?然后你应该添加唯一键。
  • 您的查询没有任何意义,每列值都将在返回的不同“col_name”列表中。

标签: mysql sql-delete mysql-error-1093


【解决方案1】:

您必须使用别名。

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

它应该可以工作。

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

【讨论】:

  • 我使用了这个确切的语法并且没有错误,但也没有任何内容被删除,即表没有改变并且仍然包含条目。我验证是否存在重复条目:select col_name from table group by col_name having count(*)>1;
  • 检查 select a.col_name from (select distinct col_name from table) a return the line that you want 。编辑:在您的情况下,检查 select a.col_name from (select col_name from table group by col_name with count(*)>1) a return something。如果没有,请检查内部查询。
  • 谢谢,我检查了select a.col_name from (select col_name from table group by col_name having count(*)>1) a,它确实返回了我想删除的行,所以我使用了这个-> 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) 而不是上面的语法,这很有效!我仍然不确定为什么您建议的第一件事不起作用...
  • @jeffery_the_wind 它不起作用,因为首先您选择所有不同的 col_name 然后您说“col_name 不在(...)中”,显然每个 col_name 都将在返回的不同列表中,所以什么都没有已删除。
【解决方案2】:

@Molochdaa 接受的答案是错误的

解释。 假设这是桌子

col_name |  value
------------------
east     |  10
west     |  15
east     |  10
west     |  15
north    |  5
east     |  10
north    |  5

select distinct col_name from table_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..)

【讨论】:

    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 2016-07-03
    • 2013-01-17
    相关资源
    最近更新 更多