Deleting a row based on the max value

前端 未结 4 1239
我在风中等你
我在风中等你 2020-12-03 18:23

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

I tried

WHERE jobPositonId = max(jobPostionId)

but got

相关标签:
4条回答
  • 2020-12-03 18:49

    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.

    0 讨论(0)
  • 2020-12-03 18:53

    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?

    0 讨论(0)
  • 2020-12-03 18:56
    DELETE FROM table ORDER BY jobPositonId DESC LIMIT 1
    
    0 讨论(0)
  • 2020-12-03 19:05
    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)
    
    0 讨论(0)
提交回复
热议问题