Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get around self-referencing in a DELETE query

Tags:

mysql

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

like image 680
DonutReply Avatar asked Jan 05 '11 17:01

DonutReply


1 Answers

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)  
like image 174
Martin Smith Avatar answered Sep 21 '22 18:09

Martin Smith