1.需求:mysql删除字段数据重复的数据,只保留一条
1.先看我表中数据(id为主键)想直接看结果拉倒第七步,看分析过程的一步一步往下看
2.测试:我们想要的结果是删除表中user_name和password都相同的数据,即图中的标记1和2(第三天先圈住,看后面解释)
3.先根据user_name和password分组并取出数量大于1的数据
SELECT * FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1
4.第三步已经把user_name和password都重复的数据已经查出来了,然后我们在最外层再套一层查询,把user_name和password在第三步的结果集中的数据取出来,是不是就可以查询来这两个字段都重复的所有数据的id是多少(因为id是唯一的,第一步已经说了,我们要根据id删除重复数据,这里最外层查询我先查所有,以便于和第一步的数据作对比)
注:图中的两个条件缺一不可,否则会把第一步中的标记3也会查出来
SELECT
*
FROM
student t1
WHERE
t1.user_name IN ( SELECT t.user_name FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 ) and
t1.PASSWORD IN ( SELECT t.PASSWORD FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 ) )
5.第四步已经把所有重复数据的id取出来了,然后我们从重复的数据里面取一条id最大的,作为保留的数据(这里最外层查询我先查所有)
SELECT
*
FROM
student t1
WHERE
t1.user_name IN ( SELECT t.user_name FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 ) and
t1.PASSWORD IN ( SELECT t.PASSWORD FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 )
AND t1.id NOT IN (
SELECT
max( t.id ) as id
FROM
student t
GROUP BY
t.PASSWORD,
t.user_name
HAVING
count( 1 ) > 1
)
6.第五步已经把id查出来了,那么第六步就是删除id在第五步结果集中的数据,但是如果直接在最外层加delete是不行的,会报
You can’t specify target table ‘student’ for update in FROM clause,这个错误的意思是不能在同一个sql语句中,先select同一个表的某些值,然后再delete这个表。因此需要再套一层查询
DELETE from student where id in (
SELECT
t1.id as id
FROM
student t1
WHERE
t1.user_name IN ( SELECT t.user_name FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 )
AND t1.PASSWORD IN ( SELECT t.PASSWORD FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 )
AND t1.id NOT IN (
SELECT
max( t.id ) AS id
FROM
student t
GROUP BY
t.PASSWORD,
t.user_name
HAVING
count( 1 ) > 1
))
在这里插入图片描述7.此sql为最终结果
总结:如果删除有几个字段重复的,就group by几个字段值,然后第四步要加所有的in条件
需求:mysql删除字段数据重复的数据,全部删除,一条都不保留
把最后一个附加条件去掉
DELETE from student where id in (
SELECT tt.id as id from (
SELECT
t1.id as id
FROM
student t1
WHERE
t1.user_name IN ( SELECT t.user_name FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 )
AND t1.PASSWORD IN ( SELECT t.PASSWORD FROM student t GROUP BY t.PASSWORD, t.user_name HAVING count( 1 ) > 1 )
)tt)
新手上路,车技不好,请各位扶好。希望大家多多支持,祝大家前程什锦,money不断。为了美好的明天,让我们一起努力吧!