删除基于三个字段和两个表的重复数据

时间:2017-07-19 21:04:49

标签: sql ms-access ms-access-2013

我有两个表,每个表有三个以上的字段。两个文件都有一组记录,下面是一个模拟示例:

表1:

ID Name Town State 1 Dave Chicago IL 2 Mark Tea MD

表2:

ID Name State Job Married 1 Dave IL Manager Yes 2 Mark MD Driver No

就我的目的而言,如果ID,名称和州相同,则存在重复。所以上面的数据是重复的。如何从一个表中删除它们(我有900多个重复项,因此无法逐个删除)?

3 个答案:

答案 0 :(得分:0)

delete table1
where ID in(select distinct ID from table1  where ID in (Select ID from table2))

我不明白哪个表有重复项,如果你想删除一个table1中的重复数据,那么你可以使用这个查询

答案 1 :(得分:0)

此查询将生成重复数据删除的结果集:

SELECT Table1.ID,
    Table1.NAME,
    Table1.Town,
    Table1.STATE,
    NULL AS Job,
    NULL AS Married
FROM Table1
WHERE Table1.ID NOT IN (
        SELECT Table1.ID
        FROM Table1
        INNER JOIN Table2 ON (Table2.STATE = Table1.STATE)
        AND (Table2.NAME = Table1.NAME)
        AND (Table1.ID = Table2.ID)
        )

UNION

SELECT Table2.ID,
    Table2.NAME,
    NULL AS Town,
    Table2.STATE,
    Table2.Job,
    Table2.Married
FROM Table2

答案 2 :(得分:0)

这是最简单的方法,假设您要从Table1中删除。我对Access SQL语法有点生疏,但我相信这有效:

DELETE FROM [Table1]
WHERE EXISTS (
    SELECT 1
    FROM [Table2]
    WHERE [Table2].[ID]      = [Table1].[ID]
        AND [Table2].[Name]  = [Table1].[Name]
        AND [Table2].[State] = [Table1].[State]
)