8

I'm trying to delete all records which aren't the latest version under their name but apparently you can't reference access a table you are modifying in the same query.

I tried this but it doesn't work for the reasons above:

DELETE FROM table
WHERE CONCAT(name, version ) NOT IN (
SELECT CONCAT( name, MAX( version ) )
FROM table
GROUP name
)

How can I get around this?

Cheers

Nick
  • 138,499
  • 22
  • 57
  • 95
DonutReply
  • 3,184
  • 6
  • 31
  • 34

2 Answers2

9

Wrap the inner reference in a derived table.

DELETE FROM table
WHERE  Concat(name, version) NOT IN (SELECT nv
                                     FROM   (SELECT Concat(name, Max(version))
                                                    AS nv
                                             FROM   table
                                             GROUP  BY name) AS derived)  
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
  • 1
    Thanks, I had seen that link and tried this method earlier but I must have left a misplaced bracket somewhere. – DonutReply Jan 05 '11 at 17:22
7
delete t1
from  table_name1 t1, table_name1 t2 
where t1.version < t2.version 
and t1.name = t2.name;

//creating alias is the need here

Angelin Nadar
  • 8,944
  • 10
  • 43
  • 53