从具有另一个表的外键的表中删除重复的行?

时间:2017-03-02 14:23:01

标签: sql database duplicates foreign-keys subquery

我有两张表employeedepartments。 员工表

ID , name ,  salary, dep_ID
1  | john |  2300  | 1
2  | smith|  1500  | 2
3  | john |  2300  | 1

此处dep_idforeign key

现在部门

id, name
1 | COMPUTER SCIENCE
2 | MATHEMATICS

现在我要做的是“删除员工表中的所有重复行”

3 个答案:

答案 0 :(得分:1)

delete  from Employee
where   id not in
        (
        select  minid
        from    (
                select  min(id) as minid
                from    Employee
                group by
                        name
                ,       salary
                ,       dep_ID
                ) sub
        )

Example at rextester.com.

答案 1 :(得分:1)

for SQL ..

在dep_ID列上添加UNIQUE索引。编写ALTER语句时,请包含IGNORE关键字:

ALTER IGNORE TABLE员工 添加UNIQUE INDEX idx_name(dep_ID);

这将删除所有重复的行,并避免将来重复插入。

答案 2 :(得分:1)

如果您不介意使用多个语句和临时表,此解决方案适用于任何dbms:

create table tmp as
select min(ID), name, salary, dep_ID
from employee
group by name, salary, dep_ID;

truncate table employee;

insert into employee
select * from tmp;

drop table tmp;
相关问题