1

好的,所以我有一个有 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
4

2 回答 2

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
于 2013-10-10T22:32:19.890 回答
1
DELETE FROM table WHERE `pid` NOT IN
(SELECT maxpid FROM
    ( SELECT MAX(`pid`) as maxpid
      FROM table
      GROUP BY `xid`
    )as m
)
于 2013-10-10T22:34:45.890 回答