使用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 |
答案 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
)