SQL语句或存储过程删除除最近的所有重复行?

时间:2017-06-27 04:41:11

标签: mysql

使用MySQL 5时,需要编写一个SQL语句(或存储过程,如果需要)从该表中删除给定设备的所有重复行,除了最新的行(最年轻的created_time)?

这是表格:

desc user_detail;

收率:

| Field           | Type         | Null | Key | Default             | Extra                       |
+-----------------+--------------+------+-----+---------------------+-----------------------------+
| user_id         | varchar(200) | NO   | PRI |                     |                             |
| device          | text         | YES  |     | NULL                |                             |
| created_time    | timestamp    | NO   |     | 0000-00-00 00:00:00 |                             |
| updated_time    | timestamp    | NO   |     | CURRENT_TIMESTAMP   | on update CURRENT_TIMESTAMP |

1 个答案:

答案 0 :(得分:1)

这可以通过exists自我加入来完成:

delete from user_detail a where exists (
    select 1 from user_detail b
    where a.device = b.device
    and b.created_time > a.created_time
)