示例数据库:
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&上保留 John 名称?乙
答案 0 :(得分: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
答案 1 :(得分:2)
禁止甚至插入此类重复项的更好方法是多列唯一索引(它也会优化您的搜索)。方法如下:
ALTER TABLE `Student`
ADD UNIQUE INDEX `idx` (`StudentName`, `StudentClass`)
答案 2 :(得分: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
注意:请先备份您的数据;我对丢失的数据不负任何责任:-)这是一个概念性的想法,尚未经过测试。
答案 3 :(得分: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。然后我们只删除与该类和名称匹配的所有内容,但是我们与最小标识不匹配,因此在一天结束时,我们保留(大概)第一条记录不重复并根除休息。