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
  • 123,192
  • 20
  • 49
  • 81
DonutReply
  • 3,136
  • 5
  • 30
  • 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
  • 419,657
  • 83
  • 708
  • 800
  • 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,556
  • 9
  • 41
  • 52