目的:去除(或删除)一个表里面手机号重复的数据,但是需要保留其中一个记录,换句话说,表里面手机号不为空的数据,一个手机有且只有一条记录

表结构:

CREATE TABLE `account` (
`id` int(11) NOT NULL,
`phone` varchar(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);

插入一些数据:

insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');
insert into account values('','');

查询一下现在表里面的重复情况:

select count(*)as num,phone from account where phone <> '' group by phone having num > 1;

查询结果:

现在我们要去除多余的手机号数据,直接把这个值置为空,删除同理,这里不再重复

SQL如下:

update account set phone='' where
phone in
(select phone from account where phone<>'' group by phone having count(id)>1)
and
id not in
(select min(id) from account where phone<>'' group by phone having count(id)>1)
;

但是执行的时候会报错:

update account set phone='' where phone in (select phone from account where phone<>'' group by phone having count(id)>1)and id not in(select min(id) from account where phone<>'' group by phone having count(id)>1)    
Error Code: 1093. You can't specify target table 'account' for update in FROM clause 0.031 sec

分析:不能先select出同一表中的某些值,再update这个表(在同一语句中)

重新写SQL(取下别名):

update account set phone='' where
phone in
(select a.phone from
(select phone from account where phone<>'' group by phone having count(id)> 1) as a
)
and
id not in
(select b.id from
(select min(id) as 'id' from account where phone<>'' group by phone having count(id)> 1) as b
)
;

执行完成之后我们再查一遍数据的情况:

select * from account;

查询结果(每个手机号只有一条记录,其他均被置空):

最新文章

  1. JQuery easyUI DataGrid 创建复杂列表头(译)
  2. powerdesinger
  3. 关于初学者Could not find action or result :No result defined for action com.lyw.action.LoginAction and result success
  4. 用一条sql语句显示数据百分比并加百分号
  5. 窗体==&gt;&gt;初始Windows程序
  6. Apache Shiro 开源权限框架
  7. 读懂diff
  8. Custom PeopleSoft Queries
  9. libnet发包例子(tcp udp arp广播)
  10. 【2012天津区域赛】部分题解 hdu4431—4441
  11. Gradle学习系列之一——Gradle快速入门(转)
  12. 对象作为 map 的 key 时,需要重写 equals 方法和 hashCode 方法
  13. 剑指offer试题(PHP篇二)
  14. mac下redis安装、设置、启动停止
  15. 使用vue-awesome-swiper的相关问题
  16. [LeetCode] Max Increase to Keep City Skyline 保持城市天际线的最大增高
  17. [UE4]抛物线指示器
  18. LeetCode(101):对称二叉树
  19. UserControl VS TemplatedControl
  20. mongodb的几种启动方法

热门文章

  1. 1146. Topological Order (25)
  2. python 日期封装
  3. web框架之初识Django
  4. iOS----收集的一些小技巧
  5. 黑苹果 MacOS 10.15 Catalina安装教程
  6. C#中如何通过点击按钮切换窗口
  7. Vue子组件传递数据给父组件
  8. HDU4405 Aeroplane chess (概率DP,转移)
  9. apache主要配置详解
  10. CSU 1551 Longest Increasing Subsequence Again(树状数组 或者 LIS变形)