从mysql表删除重复数据日期
如何从MySQL表中删除昨天的重复数据并保留最新记录?
例如,使用以下数据:
SELECT * FROM data;
| pid | serviceid | id | created
| ----| ----------|----------------|---------
| 10 | ABNCKN | Q0CHZ2GI1VKOPL | 2022-06-14 10:49:34
| 11 | ABNCKN | Q0CHZ2GI1VKOPL | 2022-06-14 10:49:34
| 12 | KSPSLS | QLSPDF0S0SDFKK | 2022-06-15 11:44:21
| 13 | AKNKSL | QLSPDF0S0SDFKK | 2022-06-15 12:51:42
| 14 | AKNKSL | QLSPDF0S0SDFKK | 2022-06-15 12:51:42
我使用
DELETE n1 FROM data n1, data n2 WHERE n1.pid < n2.pid AND n1.id = n2.id
如何删除仅删除重复项并保留昨天数据的最新PID?
预期的输出将被
SELECT * FROM data;
| pid | serviceid | id | created
| ----| ----------|----------------|---------
| 10 | ABNCKN | Q0CHZ2GI1VKOPL | 2022-06-14 10:49:34
| 11 | ABNCKN | Q0CHZ2GI1VKOPL | 2022-06-14 10:49:34
| 12 | KSPSLS | QLSPDF0S0SDFKK | 2022-06-15 11:44:21
| 14 | AKNKSL | QLSPDF0S0SDFKK | 2022-06-15 12:51:42
删除 | 13 | aknksl | QLSPDF0S0SDFKK | 2022-06-15 12:51:42
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从数据中选择ID name =“ abnckn”
&gt;&gt;此查询将获取具有特定名称的所有ID,并且限制将限制返回的行数。除一行外,基于重复的行,行的数量将是动态的。您可以将订单添加到查询中以排列它们。最后删除除一行以外的所有重复行。
SELECT id FROM data WHERE name="ABNCKN"
>> this query will get all ids with specific name, and limit will limit the the number of rows returned. The number of rows will be dynamic based on the duplicated rows except one row. and you can add ORDER BY to the query to arrange them.and finally delete all duplicated rows except one row.
不太了解为什么您将一些重复的数据保留在预期的输出中,但是您可以尝试的是使用Join获得最后一个ID,并从Where so so中删除它:
Didn't understand very well why you keep some duplicated data in the expected output but what you can try is get the last Id with a JOIN and filter it from the WHERE so is not deleted:
您可以使用自连接并将条件添加到仅删除昨天的数据:
请参阅此
对于mysql 8+,您也可以使用
row_number()
:检查此
L
You can achieve this using self join and add condition to only delete yesterday's data:
See this db<>fiddle
For MySQL 8+ you can also achieve this using
ROW_NUMBER()
:Check this db<>fiddle
Output after delete: