tags:

views:

63

answers:

4

This is based on my previous question.

I have the following table

Table1

JobPositionId | JobPositionName
     1        |      Sound
     2        |      Lights
     3        |      Sound
     4        |      Ground

How can I delete row three (Name = sound, and max position)

A: 
DELETE FROM
    Table1
WHERE
    JobPositionId = (
        SELECT
            MAX(JobPositionId)
        FROM
            Table1
        WHERE
            JobPositionName = 'Sound'
    )
Hammerite
MySQL error 1093 - can't specify target table for update in FROM clause
OMG Ponies
Really? Stupid MySQL. I remember there's some workaround for that, but I forget what it is.
Hammerite
A: 

Sorry if this doesn't take into account your "previous question" thought I'd just look at this one.

DELETE FROM Table1 WHERE jobpositionid = (SELECT MAX(jobpositionid) FROM table1 WHERE name = 'Sound');
Dante617
Okay, the other answers are better -- they are formatted much nicer than mine. :)
Dante617
MySQL error 1093 - can't specify target table for update in FROM clause
OMG Ponies
A: 

Use:

DELETE FROM TABLE t1 
       JOIN (SELECT x.jobpositionname,
                    MAX(jobPositonId) AS max_id 
               FROM TABLE x
           GROUP BY x.jobpositionname) t2 
 WHERE t1.jobPositonId  = t2.max_id
   AND t1.jobpositionname = t2.jobpositionname
   AND t2.jobpositionname = 'Sound'

As I mentioned in your previous question, using this won't trigger a MySQL 1093 error:

DELETE FROM TABLE
 WHERE JobPositionId = SELECT x.id
                         FROM (SELECT MAX(JobPositionId) AS id
                                 FROM TABLE
                                WHERE JobPositionName = 'Sound') x
OMG Ponies
Updated - forgot the column alias in the 2nd subquery.
OMG Ponies
A: 

It seems like what you are trying to do is to delete all duplicate JobPositionNames, leaving only the one with the lowest JobPositionId.

I had to do something very similar recently and found the SQL statements getting so complicated, it was much much easier (if much less efficient) to do it in SQL.

So in case this is a poluted database you're trying to clean, just write a script that does this and be done with it (and set some unique indexes to prevent it from happening again).

If this happens all the time, and needs to be done periodicaly, fix the code that does this.

Martijn