2

示例数据库:

ID StudentName StudentClass
1  John        A
2  John        B
3  Peter       A
4  John        A
5  John        B

我想要的结果应该是

ID StudentName StudentClass
1  John        A
2  John        B
3  Peter       A

声明

DELETE FROM Student
 WHERE ID NOT IN (SELECT * 
                    FROM (SELECT MIN(n.ID)
                            FROM Student n
                        GROUP BY n.StudentName) x)

我如何在A 和 B类上保留John的名字?

4

4 回答 4

2
DELETE a FROM Student a
LEFT JOIN
    (
        SELECT MIN(ID) AS minid
        FROM Student
        GROUP BY StudentName, StudentClass
    ) b ON a.id = b.minid
WHERE
    b.minid IS NULL
于 2012-07-07T03:49:52.470 回答
2

甚至禁止插入此类重复项的更好方法是多列唯一索引(它也会优化您的搜索)。方法如下:

ALTER TABLE `Student`
  ADD UNIQUE INDEX `idx` (`StudentName`, `StudentClass`)
于 2012-07-07T04:32:09.417 回答
0

您应该能够Students使用 JOIN 谓词来连接自身,以确保 JOIN 匹配重复的学生,并删除加入的行:

DELETE 
  duplicate_students.* 
FROM Students JOIN Students as duplicate_students 
  ON Students.StudentName = duplicate_students.StudentName
  AND Students.StudentClass = duplicate_students.StudentClass
  AND duplicate_students.ID > Students.ID

注意:请先备份您的数据;我对丢失的数据不承担任何责任 :-) 这是一个概念性的想法,尚未经过测试。

于 2012-07-07T03:45:21.483 回答
0

这应该有效:

DELETE S FROM Student S
INNER JOIN(
    SELECT MIN(ID) AS ID,StudentName,StudentClass FROM Student
    GROUP BY StudentName,StudentClass
) S2 ON S.ID != S2.ID AND S.StudentName = S2.StudentName AND S.StudentClass = S2.StudentClass

它基本上从子查询中的所有重复记录中选择最小 ID。然后我们简单地删除与该类和名称匹配的所有内容,但我们不匹配最小 ID,因此在一天结束时,我们将(可能)保留第一个记录而不是重复记录并消除休息。

于 2012-07-07T05:12:26.340 回答