sql delete duplicate data, keep one, and keep update_time biggest piece

Recent interview, the examiner out of a question, did not make it. The next day the idea came of it, written, hereby record it.

There is a table t, three fields, increment id, name, update_time, delete the name duplicate rows, reserved update_time that the biggest one, leaving only a

DELETE
FROM
    t
WHERE
    t.`name` IN (
        SELECT
            t.`name`
        FROM
            (SELECT * FROM t) t
        GROUP BY
            t.`name`
        HAVING
            count(1) > 1
    )
AND t.id NOT IN (
    SELECT
        substring_index(max(t.new_u_time), ',', - 1)
    FROM
        (
            SELECT
                t.id,
                t.`name`,
                t.update_time,
                CONCAT(t.update_time, ',', t.id) new_u_time
            FROM
                t
        ) t
    GROUP BY
        t.`name`
    HAVING
        count(1) > 1
)



Note: If you are easily removed, leaving a line, that we should all, this is possible update_time duplicate happens, so it is necessary update_time and id concat up, and then take the maximum, so you do not repeat it

Guess you like

Origin www.cnblogs.com/theone67/p/12515666.html