Chinaunix首页 | 论坛 | 博客
  • 博客访问: 416270
  • 博文数量: 43
  • 博客积分: 613
  • 博客等级: 中士
  • 技术积分: 756
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-01 11:25
文章分类

全部博文(43)

文章存档

2016年(1)

2015年(5)

2014年(5)

2013年(14)

2012年(18)

分类: Mysql/postgreSQL

2012-11-13 18:22:48

表结构如下:

  1. mysql> desc source_user_data;
  2. +--------------+------------------+------+-----+---------+----------------+
  3. | Field | Type | Null | Key | Default | Extra |
  4. +--------------+------------------+------+-----+---------+----------------+
  5. | id | int(10) unsigned | NO | PRI | NULL | auto_increment |
  6. | username | varchar(255) | YES | | NULL | |
  7. | mobile_phone | varchar(30) | YES | | NULL | |
  8. | email | varchar(60) | NO | MUL | NULL | |
  9. | province | varchar(50) | YES | | NULL | |
  10. | city | varchar(50) | YES | | NULL | |
  11. | post | varchar(50) | YES | | NULL | |
  12. | is_jianli | double | YES | | NULL | |
  13. +--------------+------------------+------+-----+---------+----------------+

使用delete删出表数据的时候,使用如下语句报错:

  1. mysql> DELETE FROM `source_user_data`
  2.     -> WHERE email IN (SELECT email FROM source_user_data GROUP BY email HAVING COUNT(*) > 1)
  3.     -> AND id NOT IN (SELECT MIN(id) FROM source_user_data GROUP BY email HAVING COUNT(*)>1);
  4. ERROR 1093 (HY000): You can't specify target table 'source_user_data

文档中说:

 

 

In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

DELETE FROM t WHERE ... (SELECT ... FROM t ...);UPDATE t ... WHERE col = (SELECT ... FROM t ...);{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the

FROM

clause. Example:

UPDATE t ... WHERE col = (SELECT (SELECT ... FROM t...) AS _t ...);

Here the prohibition does not apply because a subquery in the

FROM

clause is materialized as a temporary table, so the relevant rows in

t

have already been selected by the time the update to

t

大概就是说要把子查询当成个临时表启个别名再套一层。

好吧,修改成以下的SQL就通过了:

  1. mysql> DELETE FROM source_user_data WHERE email IN (SELECT a.email FROM (SELECT b.* FROM source_user_data b GROUP BY b.email HAVING COUNT(b.email) > 1) a)
  2.     -> AND id NOT IN (SELECT d.id FROM (SELECT MIN(c.id) AS id FROM source_user_data c GROUP BY email HAVING COUNT(email)>1) d);
  3. Query OK, 1 row affected (0.12 sec)


 




 

阅读(1750) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~