9

How can I structure a mySQL query to delete a row based on the max value.

I tried

WHERE jobPositonId = max(jobPostionId)

but got an error?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Robert de Klerk
  • 604
  • 3
  • 12
  • 23
  • 2
    I would advise against that. How come you don't know a certain id of the row to be deleted? – Your Common Sense Sep 01 '10 at 18:27
  • @Common Sense, as the question states, the desired row to be deleted is the row which is defined by a max value (rather than a row defined by an id). This would accomplish in one query what you might propose to do in two? That is, query for the id of the max row; then delete that row. – Aaron Oct 15 '15 at 05:21

4 Answers4

18
DELETE FROM table ORDER BY jobPositonId DESC LIMIT 1
Konerak
  • 37,118
  • 11
  • 93
  • 114
16

Use:

DELETE FROM TABLE t1 
       JOIN (SELECT MAX(jobPositonId) AS max_id FROM TABLE) t2 
 WHERE t1.jobPositonId  = t2.max_id

Mind that all the rows with that jobPositonId value will be removed, if there are duplicates.

The stupid part about the 1093 error is that you can get around it by placing a subquery between the self reference:

DELETE FROM TABLE
 WHERE jobPositonId = (SELECT x.id
                         FROM (SELECT MAX(t.jobPostionId) AS id 
                                 FROM TABLE t) x)

Explanation

MySQL is only checking, when using UPDATE & DELETE statements, if the there's a first level subquery to the same table that is being updated. That's why putting it in a second level (or deeper) subquery alternative works. But it's only checking subqueries - the JOIN syntax is logically equivalent, but doesn't trigger the error.

OMG Ponies
  • 300,587
  • 73
  • 490
  • 482
0

This works:

SELECT @lastid := max(jobPositonId ) from t1; 
DELETE from t1 WHERE jobPositonId = @lastid ; 

Other than going to the database twice, is there anything wrong with this technique?

sdfor
  • 5,786
  • 11
  • 47
  • 59
0
DELETE FROM `table_name` WHERE jobPositonId = (select max(jobPostionId) from `table_name` limit 1)

OR

DELETE FROM `table_name` WHERE jobPositonId IN (select max(jobPostionId) from `table_name` limit 1)
el_quick
  • 4,390
  • 11
  • 38
  • 51