MySQL DELETE使用有和计数的子查询

时间:2011-02-08 18:29:19

标签: mysql mysql-error-1093

尝试使用以下查询删除多个条目:

首先,我使用此查询找到要删除的条目:

SELECT guid FROM account GROUP BY guid,type HAVING count(type) > 1);

然后我将此查询添加到DELETE语句:

DELETE FROM account WHERE guid IN (SELECT guid FROM account GROUP BY guid,type HAVING count(type) > 1);

但是我收到了这个错误:

您无法在FROM子句

中为更新指定目标表'account'

3 个答案:

答案 0 :(得分:1)

我认为您需要使用临时表来满足您的需求,如下所示:

  1. 步骤1:创建临时表

    CREATE TEMPORARY TABLE MyTemp
    SELECT guid FROM account 
    GROUP BY guid,type HAVING count(type) > 1;
    
  2. 使用删除语句中的临时表

    DELETE FROM account 
    WHERE guid IN (SELECT guid FROM MyTemp);
    
  3. 删除临时表

    DROP TEMPORARY TABLE MyTemp;
    
  4. 编辑:我认为使用* 两个嵌套表的解决方案也有效:

      DELETE FROM account 
        WHERE guid IN 
         (SELECT guid FROM 
           (SELECT guid FROM account 
           GROUP BY guid,type HAVING count(type) > 1) as MyTemp
        )
    

答案 1 :(得分:0)

您的问题已解决,请执行以下操作..

    DELETE FROM account 

      WHERE guid IN 

     (SELECT * FROM 

       (SELECT guid FROM account 

          GROUP BY guid,type 

          HAVING  count(type) > 1) AS a);

答案 2 :(得分:-1)

首先创建视图

create view view_acct as 
SELECT guid FROM account 
GROUP BY guid,type HAVING count(type) > 1;

使用视图后

DELETE FROM account WHERE guid in (select * from view_acct);