Sql查询删除特定条件的行

时间:2013-05-24 07:50:26

标签: mysql sql

我正在尝试为以下

编写查询

mysql db有两列数据如下

no id
1   1
1   2
1   3
2   4
3   5
3   6
4   7
5   8

我需要为以下条件编写查询

当“否”重复时,从db中删除所有那些行,其中“no”相同,“id”>那个“不”的身份分钟

expected output for the above table
no id
1   1
2   4 
3   5
4   7
5   8

2 个答案:

答案 0 :(得分:3)

DELETE  a
FROM    tableName a
        LEFT JOIN
        (
            SELECT  no, MIN(ID) min_ID
            FROM    tableName
            GROUP   BY no
        ) b ON a.no = b.no AND
                a.id = b.min_ID
WHERE   b.no IS NULL

另一种方式,

DELETE  a
FROM    tableName a
        INNER JOIN tableName b 
        ON a.no = b.no
WHERE   a.id > b.id

答案 1 :(得分:0)

DELETE FROM tableName WHERE id NOT IN (
    SELECT MIN(id) FROM tableName GROUP BY no
)

HTH