⼀条sql语句完成MySQL去重留⼀
⾃⼰百度
到了⼀条sql语句:
DELETE
FROM
vitae a
WHERE
(a.peopleId, a.seq) IN (
SELECT
peopleId,
seq
FROM
vitae
GROUP BY
peopleId,
seq
HAVING
count(*) > 1
)
AND rowid NOT IN (
SELECT
min(rowid)
mysql删除重复的数据保留一条
FROM
vitae
GROUP BY
peopleId,
seq
HAVING
count(*) > 1
)
这条语句是在 【MySQL中删除重复数据只保留⼀条】 这篇⽂章⾥到的。这条sql思路很明显,有以下3步:
SELECT peopleId, seq FROM vitae GROUP BY peopleId, seq HAVING count(*) > 1 查询出表中重复记录作为条件
SELECT min(rowid) FROM vitae GROUP BY peopleId, seq HAVING count(*) > 1 查询出表中重复记录中ID最⼩的值为第⼆个条件
最后根据以上两个条件,删除 除 重复记录中最⼩ID的其余重复记录
但是很⽆奈的是,运⾏这条语句出现了错误,⼤致报错意思是,不能在查询的时候同时更新这个表。
代码解决
根据上⾯这个sql语句想到或许可以通过代码的⽅式,两步来达到同样的⽬的:
先取出重复的数据集
根据查询到的数据集,循环删除其余的重复数据
想法是有了,写出来也很快,但是⼀运⾏吓我⼀跳,竟然需要 116s 左右,然后⾃⼰就想⼀定要到可以使⽤的sql语句,贴⼀下代码和运⾏结果:
完美的【去重留⼀】SQL
最后在⼀个技术⾥得到了完美的答案,看这条sql语句:
DELETE consum_record
FROM
consum_record,
(
SELECT
min(id) id,
user_id,
monetary,
consume_time
FROM
consum_record
GROUP BY
user_id,
monetary,
consume_time
HAVING
count(*) > 1
) t2
WHERE
consum_record.user_id = t2.user_id
and ary = t2.monetary
and sume_time = t2.consume_time
AND consum_record.id > t2.id;
上⾯这条sql语句,仔细看⼀下,揣摩出思路也不难,⼤概也分为3步来理解:
(SELECT min(id) id, user_id, monetary, consume_time FROM consum_record GROUP BY user_id, monetary, consume_time HAVING count(*) > 1 ) t2 查询出重复记录形成⼀个集合(临时表t2),集合⾥是每种重复记录的最⼩ID
consum_record.user_id = t2.user_id and ary = t2.monetary and sume_time =
根据条件,删除原表中id⼤于t2中id的记录
看到这个语句的时候,⼼⾥想这也太厉害了。这么⼀个简单的sql语句,竟然可以解决这么复杂的问题,涨姿势了~
运⾏起来也超级快,原先的代码循环执⾏,需要 116s 左右,⽽这⾥ 0.3s 就可以了,厉害了~

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。