关于数据库去除重复记录,有什么优雅的写法

2016-11-18 22:14:16 +08:00
 pouta
delete from demo_user where id in(

//获取重复记录的 id
select id from demo_user 
where id > any (select id from demo_user where age in (select age from demo_user group by age having count(age) > 1))
and id <= some (select id from demo_user where age in (select age from demo_user group by age having count(age) > 1))

);

报了 error: You can't specify target table 'demo_user' for update in FROM clause

4063 次点击
所在节点    MySQL
12 条回复
20150517
2016-11-19 00:00:04 +08:00
先要删的记录先 insert into xxxx (select xxx from xxxx)
然后再 delete from xxx where id in (select xxx from xxxx)
Layne
2016-11-19 00:50:02 +08:00
楼上说的这是流着泪积累的经验,楼主你值得拥有。。
ihuotui
2016-11-19 01:05:43 +08:00
就是用一个 id 唯一索引的表保存一次,然后改表名,即有备份又得到结果
dalang
2016-11-19 07:44:22 +08:00
我一般都是先把要操作的 table duplicate 一份
caomaocao
2016-11-19 09:18:21 +08:00
@20150517 老司机经验啊!
pouta
2016-11-19 09:44:12 +08:00
@20150517 就是说要删除的记录 先保存下来是吗
rockpk008
2016-11-19 09:46:43 +08:00
一楼绝壁有过故事
pouta
2016-11-19 09:50:10 +08:00
@dalang 我现在是学 看各位有没有更好的写法
lrh3321
2016-11-19 16:05:17 +08:00
@pouta 批量删除和改数据前,最好先备份。 至少能保证 SQL 写错了的时候,你可以回档。

删库跑路并不是说着玩的
pouta
2016-11-19 16:36:37 +08:00
@lrh3321 所以各位能不能看下我写的 sql 语句
20150517
2016-11-20 00:31:46 +08:00
@rockpk008 哈哈,数据工程师多年,泪的教训太多了...不过我说的 insert 是 insert 主键就够了
20150517
2016-11-20 00:33:30 +08:00
@pouta 你要确定没问题就只保存主键,要是数据重要,量又不大,就先拷一份咯

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/321595

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX