1. 程式人生 > >mysql 刪除重複只只保留一條記錄

mysql 刪除重複只只保留一條記錄

建表語句以及資料如下:

create table `staff` (
    `id` bigint (20),
    `name` varchar (60)
); 
insert into `staff` (`id`, `name`) values('1','張三');
insert into `staff` (`id`, `name`) values('2','李四');
insert into `staff` (`id`, `name`) values('3','王五');
insert into `staff` (`id`, `name`) values('4','趙六');
insert into `staff` (`id`, `name`) values('
5','王五'); insert into `staff` (`id`, `name`) values('6','王五'); insert into `staff` (`id`, `name`) values('7','李四'); insert into `staff` (`id`, `name`) values('8','趙六'); insert into `staff` (`id`, `name`) values('9','趙六');

刪除一條記錄,不考慮其他條件一:

DELETE
FROM
  staff
WHERE id NOT IN
  (SELECT id FROM (SELECT
id FROM staff GROUP BY NAME) t );

刪除一條記錄,保留id最新值:

-- 刪除重複值,只保留一條最小記錄
DELETE
FROM
  staff
WHERE NAME IN
  (SELECT
    NAME
  FROM
    (SELECT
      NAME
    FROM
      staff t1
    GROUP BY t1.name
    HAVING COUNT(t1.name) > 1) t3)

  AND id NOT IN
  ( SELECT id FROM (SELECT
    MIN
(t2.id) AS id FROM staff t2 GROUP BY t2.name HAVING COUNT(t2.name) > 1) t4 );

– 刪除重複值,只保留一條最大記錄

   -- 刪除重複值,只保留一條最大記錄
DELETE
FROM
  staff
WHERE NAME IN
  (SELECT
    NAME
  FROM
    (SELECT
      NAME
    FROM
      staff t1
    GROUP BY t1.name
    HAVING COUNT(t1.name) > 1) t3)

  AND id NOT IN
  ( SELECT id FROM (SELECT
    MAX(t2.id) AS id
  FROM
    staff t2
  GROUP BY t2.name
  HAVING COUNT(t2.name) > 1) t4 );