欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

删除数据库表中某一字段相同的数据,并保留最新一条---Mysql

程序员文章站 2022-06-05 11:28:46
...


今天碰到一个题,假如有一个person表,有id,和name两个字段,如果要删除存在name相同的字段的数据,并保留最新一条,sql怎么设计?

原本的设计如下,但是运行出错

DELETE FROM person
WHERE (pname IN
  (SELECT pname
  FROM person
  GROUP BY pname
  HAVING COUNT(pname) > 1)) AND (id NOT IN
  (SELECT MIN(id)
  FROM person
  GROUP BY pname
  HAVING COUNT(pname) > 1));

错误原因:You can't specify target table for update in FROM clause

翻译过来的意思是:不能先select出同一表中的某些值,再update这个表(在同一语句中).

正确的写法是:

DELETE
FROM
  person
WHERE
  (
    pname IN (
      SELECT
        n. pname
      FROM
        (
          SELECT
            pname
          FROM
            person
          GROUP BY
            pname
          HAVING
            COUNT(pname) > 1
        ) n
    )
  )
AND (
  id NOT IN (
    SELECT
      i.id
    FROM
      (
        SELECT
          MIN(id) AS id
        FROM
          person
        GROUP BY
          pname
        HAVING
          COUNT(pname) > 1
      ) i
  )
);