0

我正在尝试为以下内容编写查询

mysql db有两列数据如下

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

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

当 "no" 重复时,从 db 中删除 "no" 相同且 "id" > min of id for that "no" 的所有行

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

2 回答 2

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
于 2013-05-24T07:52:15.513 回答
0
DELETE FROM tableName WHERE id NOT IN (
    SELECT MIN(id) FROM tableName GROUP BY no
)

高温高压

于 2013-05-24T07:54:36.083 回答