开发者

Deleting with Max

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)开发者_如何转开发


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


DELETE FROM
    Table1
WHERE
    JobPositionId = (
        SELECT
            MAX(JobPositionId)
        FROM
            Table1
        WHERE
            JobPositionName = 'Sound'
    )


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');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜