Pregunta

Okay so I have a table that has xid. Each xid can have several pids. I am trying to delete everything except the row that has the highest pid for each xid.

I am trying:

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

If I use the same query but with SELECT instead of DELETE, I get all of the records that I want to delete. When the DELETE is there, I get the error:

#1093 - You can't specify target table 'mod_personnel' for update in FROM clause
¿Fue útil?

Solución

Use a JOIN rather than 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

Otros consejos

DELETE FROM table WHERE `pid` NOT IN
(SELECT maxpid FROM
    ( SELECT MAX(`pid`) as maxpid
      FROM table
      GROUP BY `xid`
    )as m
)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top