以下代码返回特定列的重复行列表。在这种情况下,我试图找到重复的大学名称。我的问题是如何删除重复项并为每个不同的university_name留下一个副本?
Select * from `university` where `university_name` in ( select `university_name` from `university` group by `university_name` having count(*) > 1 )
结果如下:
答案 0 :(得分:3)
1)如果你想保持id值最低的行:
DELETE a
FROM university a, university b
WHERE a.id > b.id
AND b.university_name=a.university_name
2)如果你想保留id值最高的行:
DELETE a
FROM university a, university b
WHERE a.id < b.id
AND b.university_name=a.university_name
答案 1 :(得分:1)
试试这个:
DELETE u
FROM university u
LEFT JOIN
(
SELECT MIN(ID) ID, university_name
FROM university
GROUP BY university_name
) v ON u.ID = v.ID AND
u.university_name = v.university_name
WHERE v.ID IS NULL
答案 2 :(得分:0)
删除重复项并保留具有最早ID的行
DELETE a
FROM university a
JOIN university b ON a.university_name = b.university_name
WHERE a.id > b.id