0

我有一张这样的桌子:

Country_city('id', 'country_id', 'City_id')

并在其上复制我选择的记录:

SELECT 
    CONCAT(Country_id, '+', City_id), 
    COUNT(CONCAT(Country_id, '+', City_id)) 
FROM Country_City
GROUP BY CONCAT(Country_id, '+', City_id) 
HAVING COUNT(CONCAT(Country_id, '+', City_id)) > 1

结果如下:

CONCAT(Country_id, '+', City_id)  |  COUNT(CONCAT(Country_id, '+', City_id))
MA07+11                           |  48
MA07+13                           |  5
...

我试图删除它们我执行这个:

DELETE FROM Country_City 
WHERE id NOT IN (
           SELECT MAX(id) 
           FROM Country_City 
           GROUP BY CONCAT(Country_id, '+', City_id)
           );

它不工作;我的要求有什么问题吗?如何删除重复数据并保留一条记录?

4

1 回答 1

0

尝试使用您的CONCAT(Country_id, '+', City_id)

DELETE cc FROM Country_City cc
INNER JOIN
(
               SELECT CONCAT(Country_id, '+', City_id) as cKey,MAX(id) as id 
               FROM Country_City 
               GROUP BY CONCAT(Country_id, '+', City_id)
               HAVING COUNT(CONCAT(Country_id, '+', City_id)) > 1           
) ccs on CONCAT(cc.Country_id, '+', cc.City_id) = ccs.cKey 
             and ccs.id != cc.id;

虽然CONCAT这里可能不需要,所以你也可以使用:

DELETE cc FROM Country_City cc
INNER JOIN
(
 SELECT Country_id,City_id,MAX(id) as id 
 FROM Country_City 
 GROUP BY Country_id,City_id
 HAVING COUNT(*) > 1           
) ccs on cc.Country_id = ccs.Country_id 
      and cc.City_id = ccs.City_id 
      and ccs.id != cc.id;
于 2013-11-08T10:50:14.013 回答