[英]Mysql delete records older than 7days while leaving lasr 1 record for each device_id
i have a table with device_id and date time with speed as shown below 我有一张带有device_id和日期时间的表,速度如下所示
id | device_id | server_time | speed
---+-----------+---------------------+-------
1 | 3 | 2019-06-24 13:35:37 | 25
2 | 2 | 2019-06-22 13:35:37 | 35
3 | 2 | 2019-06-27 15:15:22 | 23
4 | 3 | 2019-06-24 13:35:37 | 54
5 | 1 | 2019-06-20 13:35:37 | 55
6 | 4 | 2019-06-10 13:35:37 | 34
7 | 3 | 2019-06-24 13:35:37 | 4
8 | 1 | 2019-06-21 13:35:37 | 25
i want to delete records older than 7 days but i need to keep at least 1 record for each device_id
even its older than 7days. 我想删除7天以上的记录,但是我需要为每个
device_id
保留至少1条记录,即使它的7天以上也是如此。
How can I achieve that with mysql? 我如何用mysql实现呢?
You can run a query to get the highest ID as that was the request from your comment , and delete all rows where the time is older than 7 days, and not the highest ID for each group. 您可以运行查询以获取注释中所请求的最高ID,并删除时间超过7天的所有行,而不是每个组的最高ID。
Since MySQL can't use a subquery on its own table in update/delete queries, you can use a sub-subquery to fetch all the highest IDs grouped by the device_id
. 由于MySQL在更新/删除查询中不能在其自己的表上使用子查询,因此可以使用子子查询来获取
device_id
分组的所有最高ID。
Replace foo
with your actual table-name. 将
foo
替换为您的实际表名。
DELETE FROM foo
WHERE server_time < DATE_SUB(NOW(), INTERVAL 7 DAY)
AND id NOT IN(SELECT *
FROM (SELECT MAX(id)
FROM foo
GROUP BY device_id
) AS t)
Use row_number()
使用
row_number()
delete from
(
select *, row_number() over(partition by device_id order by server_time desc) as rn
from tablename where server_Time>=NOW() - INTERVAL 7 DAY
)A where rn<>1
I would write this as join
: 我将其写为
join
:
delete t
from <table> t join
(select device_id,
max(server_time) as max_server_time,
max(id) as max_id
from <table> t2
group by device_id
) t2
on t.device_id = t2.device_id
where t.id < t2.max_id and
t.server_time < t2.max_server_time - interval 7 day;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.