Mysql 表数据查重、去重操作

表 client

按照 client_id 字段查重,查出 client_id 重复的字段的 id :

SELECT c.id
from client c
where c.client_id
in (
  SELECT c.client_id      #, COUNT(*)
  from client c
  group by c.client_id
  having COUNT(*) > 1

)

表数据去重操作,删除 client_id 重复的字段:

delete from client    # mysql 删除时,不能使用表别名
where
id
in (

select temp.id from (         # mysql 把结果集当作一个表,那就需要再自我查询一遍。否则报错 You can't specify target table '表名' for update in FROM clause。Oracle 和 SqlServer 不会出现这个问题。

  select c.id
  from client c
  where c.client_id
  in (
    SELECT c.client_id    #, COUNT(*)
   from client c
   group by c.client_id
   having COUNT(*) > 1
  )

) temp

)

sql 查重去重 是我见过两次的面试题。

猜你喜欢

转载自blog.csdn.net/beguile/article/details/88625921