既可以作为'DELETE'的目标,也可以作为单独的数据源

时间:2017-06-21 09:36:36

标签: mysql sql database

我的SQL是:

delete  from user 
where cid in (select  cid  from user group  by  cid   having  count(cid) > 1)
and id not in (select min(id) from  user  group by cid  having count(cid )>1)

提示错误消息:

  

表'user'被指定两次,既作为'DELETE'的目标又作为   一个单独的数据来源

如何解决此问题

1 个答案:

答案 0 :(得分:2)

你试过了吗?

CREATE TABLE user
    (`cid` int, `username` varchar(50))
;

INSERT INTO user
    (`cid`, `username`)
VALUES
    (1, 'John'),
    (1, 'John'),
    (2, 'Paul'),
    (2, 'Paul'),
    (3, 'Ryan')
;

DELETE FROM user 
 WHERE cid IN
   ( SELECT todel.cid
       FROM (SELECT * FROM user todel
             WHERE todel.cid 
              IN (
                       SELECT t1.cid  
                         FROM user t1
                     GROUP BY t1.cid   
                       HAVING COUNT(t1.cid) > 1
               )
              AND todel.cid 
                NOT IN (
                       SELECT MIN(t2.cid)  
                         FROM user t2
                     GROUP BY t2.cid   
                       HAVING COUNT(t2.cid) > 1
                      )              
            ) as todel
   )

由于对stackoverflow的一些研究,我发现了这个: Delete - I can't specify target table?

听起来就像你遇到的问题一样。