我有一个像这样的数据表
+------------+-------------+---------------+---------------------+
| 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
列中为其加上时间戳。有时脚本可能每天运行多次,但我只想保留当天的最新值。我想弄清楚如何只保留给定日期内每个facebook_id
的最新记录。
我尝试了一个子查询:
delete from dailydata
where date='2016-01-15' and asof != (select max(asof) from dailydata);
给了我错误
ERROR 1093(HY000):您无法在FROM子句中指定目标表'dailydata'进行更新
然后在这里进行了一些研究,并发现了有这个错误的人提出的其他一些问题(MySQL Error 1093 - Can't specify target table for update in FROM clause和You can't specify target table for update in FROM clause。他们建议使用“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
);
但我仍然遇到同样的错误。有没有人对我缺少的东西有任何想法?
答案 0 :(得分:1)
试试这个:
delete from dailydata
where date='2016-01-15'
and asof not in (select * from (select max(asof) from dailydata) as t);
答案 1 :(得分:0)
我建议为此目的使用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;