DELETE FROM table WHERE NOT MAX

时间:2013-10-10 22:21:16

标签: mysql sql max notin

好的,我有一张有xid的表。每个xid可以有几个pid。我试图删除除了每个xid具有最高pid的行之外的所有内容。

我在尝试:

DELETE FROM table WHERE `pid` NOT IN
( SELECT MAX(`pid`)
  FROM table
  GROUP BY `xid`
)

如果我使用相同的查询但使用SELECT而不是DELETE,我会获得所有要删除的记录。当DELETE存在时,我收到错误:

#1093 - You can't specify target table 'mod_personnel' for update in FROM clause

2 个答案:

答案 0 :(得分:2)

使用JOIN而不是NOT IN

DELETE t1.* FROM table t1
LEFT JOIN (SELECT xid, MAX(pid) pid
           FROM table
           GROUP BY xid) t2
ON t1.pid = t2.pid
WHERE t2.pid IS NULL

答案 1 :(得分:2)

DELETE FROM table WHERE `pid` NOT IN
(SELECT maxpid FROM
    ( SELECT MAX(`pid`) as maxpid
      FROM table
      GROUP BY `xid`
    )as m
)