我遇到的情况我认为可以与 CamelCamelCamel、Keepa 等服务进行比较。
假设我每天跟踪几个国家/地区的一篇文章的价格。所以我的桌子,我们称之为Trend
,看起来像这样
Id Created ArticleId Country Price
-------------------------------------------------
01 19/11/05 452 US 45.90
02 19/11/05 452 CA 52.99
03 19/11/05 452 MX 99.99
04 19/11/06 452 US 20.00
05 19/11/06 452 CA 25.00
06 19/11/06 452 MX 50.00
...
97 19/11/05 738 US 12.99
98 19/11/05 738 CA 17.50
99 19/11/05 738 MX 45.50
所以第二天我想更新Trend
桌子。如果一个国家/地区的价格仍然相同,我会跳过文章/国家/地区组合。如果有新价格我会添加新记录。
现在我想查询表以获取每个ArticleId
/ Country
组合。但只有它的最后一条记录(按时间戳排序)。所以以上面的例子为例,我希望得到记录04
, 05
and 06
for ArticleId
452
. Not 01
, 02
and 03
所以我从这个基本查询开始。但我该如何改变它才能获得预期的结果呢?
SELECT
*
FROM
Trend
ORDER BY
Created DESC
一种方法使用相关子查询进行过滤:
select t.*
from trend t
where t.created = (
select max(t1.created)
from trend t1
where t1.articleId = t.articleId and t1.country = t.country
)
为了性能,您需要一个索引(articleId, country, created)
.
您可能还想考虑反left join
方法:
select t.*
from trend t
left join trend t1
on t1.articleId = t.articleId
and t1.country = t.country
and t1.created > t.created
where t1.articleId is null
最后,另一个典型的解决方案是使用聚合查询来连接表:
select t.*
from trend t
inner join (
select articleId, country, max(created) created
from trend
group by articleId, country
) t1
on t1.articleId = t.articleId
and t1.country = t.country
and t1.created = t.created
哪种解决方案性能更好取决于数据的大小和分布。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)