如何删除重复的行,但仅当两个字段相等时才能删除。例如.. 在下表中,只删除One Atlanta记录,因为City Field不仅匹配,而且外键匹配也匹配。但由于外键不同,达拉斯不会被删除。
+----+-----------------+----------+
| id | City | FK |
+----+-----------------+----------+
| 1 | Los Angeles | 2 |
| 2 | Dallas | 5 |
| 3 | Dallas | 8 |
| 4 | Atlanta | 12 |
| 5 | Atlanta | 12 |
| 6 | New York City | 31 |
+----+-----------------+----------+
答案 0 :(得分:0)
我们获得最大ID,以防城市和FK相同并删除除了城市和FK重复的最大ID条目之外的所有其他条目
DELETE A
FROM TableA A join
(SELECT MAX(id), City, FK
from TableA
group by City,FK
having count(*) > 1
) AA
on A.City = AA.City
and A.FK = AA.FK
and A.id < AA.id
答案 1 :(得分:0)
试试这个:
Delete from MyTable where id in
(select T1.id from MyTable T1 where T1.id in
(select T2.id from MyTable T2 where T2.city = T1.City and T2.fk= T1.fk) )
and id not in (select MAX(id) from MyTable where id in
(select T1.id from MyTable T1 where T1.id in
(select T2.id from MyTable T2 where T2.city = T1.City and T2.fk= T1.fk)))
答案 2 :(得分:0)