利用聚合函数来去重

select * FROM `test` 
WHERE `name` in (
  select a.`name` from(
    SELECT `name` FROM `test` GROUP BY `name` HAVING COUNT(*) >1
  )a
)
and `id` not in (
  select b.`id` from(
    select min(`id`) as id from test group by `name` having count(*)>1
  )b
)

主要思路是IN和NOT IN,用IN来查出哪些是重复的,然后用NOT IN来保留一条;

每个子查询中通过HAVING函数来判断重复;

MySQL中不能在更新或删除表的同时去查询这个表,因此需要增加一个字表,否则会报错:

 You can't specify target table 'test' for update in FROM clause

 

posted @ 2018-01-13 19:03  at0x7c00  阅读(418)  评论(0)    收藏  举报
CSDN - ITeye - GitHub  |  HuQiao's Blog  |  业余经营:IT快报