how to delete duplicate rows from a table in mysql(如何从mysql中的表中删除重复的行)
问题描述
我需要从mysql的表中删除重复的记录.所以我有一个表名员工"字段是 empid、empname、empssn
I need to delete duplicate record from table in mysql. So i have a table name "employee" fields are empid, empname, empssn
为了获得重复记录,我写了一个查询
for getting duplicate record i have written a query
SELECT COUNT(empssn), empssn
FROM employee
GROUP BY empssn
HAVING COUNT(empssn)>1
现在我想删除重复的记录.为此我写了查询是.
Now i want to delete duplicate records. for that i have written query is.
DELETE FROM employee
WHERE (empid, empssn) NOT IN (SELECT MIN(empid), empssn
FROM employee
GROUP BY empssn);
你可以假设表中的记录是
you can assume records in table are
EmpId EmpName EmpSSN
-------------------------------
1 Jack 555-55-5555
2 Joe 555-56-5555
3 Fred 555-57-5555
4 Mike 555-58-5555
5 Cathy 555-59-5555
6 Lisa 555-70-5555
7 Jack 555-55-5555
8 Mike 555-58-5555
9 Cathy 555-59-5555
10 Lisa 555-70-5555
11 Lisa 555-70-5555
但我有一个mysql错误是
but i have a mysql error is
不能在 FROM 子句中指定目标表 'employee' 进行更新
You can't specify target table 'employee' for update in FROM clause
推荐答案
将其包装到派生表中的技巧是否适用于这种情况?(基于 http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/)
Does the trick of wrapping it into a derived table work for this case? (Based on http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/)
DELETE FROM employee WHERE (empid, empssn) NOT IN
(
SELECT empid, empssn FROM
(
SELECT MIN(empid) AS empid, empssn FROM employee GROUP BY empssn
) X
);
编辑是的,它似乎可以做到这一点.
Edit Yep it seems to work this end.
这篇关于如何从mysql中的表中删除重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从mysql中的表中删除重复的行
基础教程推荐
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01