繁体   English   中英

删除同一MySQL表中除最近记录以外的所有记录

[英]Deleting all but the most recent record in same mySQL table

我有这样的数据表

+------------+-------------+---------------+---------------------+
| date       | facebook_id | FB_page_likes | asof                |
+------------+-------------+---------------+---------------------+
| 2016-01-15 | person1     |        119339 | 2016-01-15 11:22:20 |
| 2016-01-15 | person1     |        119340 | 2016-01-15 11:34:00 |
| 2016-01-15 | person2     |         52147 | 2016-01-15 11:22:20 |
| 2016-01-15 | person2     |         52147 | 2016-01-15 11:34:00 |

我有一个Python脚本,该脚本会自动读取FB_page_likes值,然后在asof列中asof时间戳。 有时,脚本每天可能运行不止一次,但是我只想保留当天的最新值。 我试图弄清楚如何在给定的一天中仅保留每个facebook_id最新记录。

我试过一个子查询:

delete from dailydata 
where date='2016-01-15' and asof != (select max(asof) from dailydata);

这给了我错误

错误1093(HY000):您无法在FROM子句中指定目标表“ dailydata”进行更新

然后在这里做了一些研究,从有这个错误的人那里找到了其他一些问题( MySQL错误1093-无法在FROM子句中指定要更新的目标表,而在FROM子句 中无法指定要更新的目标表 。建议使用“ as”来避免该问题,因此我尝试了以下操作:

delete from dailydata 
where asof not in (
    select max(asof) from (
        select * from dailydata
    ) as temp 
    where date='2016-01-15' group by temp.facebook_id
);

但我仍然遇到相同的错误。 有人对我缺少的东西有任何想法吗?

尝试这个:

delete from dailydata 
where date='2016-01-15' 
and asof not in (select * from (select max(asof) from dailydata) as t);

我建议使用一个join此目的:

delete d
    from dailydata join
         (select date, max(asof) as maxasof
          from dailydata
          where date = '2016-01-15'
          group by date
         ) dd
         on d.date = dd.date and d.asof < d.maxasof;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM