这是我简化的历史记录表结构:

id | property_id | price   | created_at          | updated_at          | deleted_at
1  |      1      |   100   | 2016-04-10 01:00:00 | 2016-04-10 01:00:00 | NULL
2  |      1      |   300   | 2016-04-10 01:00:00 | 2016-04-10 01:00:00 | NULL
3  |      1      |   300   | 2016-04-10 02:00:00 | 2016-04-10 02:00:00 | NULL
4  |      2      |   200   | 2016-04-10 03:00:00 | 2016-04-10 03:00:00 | NULL
1  |      2      |   150   | 2016-04-10 04:00:00 | 2016-04-10 04:00:00 | NULL



我想获取符合特定条件的记录,尤其是created_at字段在过去24小时内
我需要获取#1中的记录之前的记录
进一步筛选结果为#1,以使其price列的记录历史记录中的值不同于-1的记录


我在#2和#3中确实有问题,尤其是过滤结果。我不想通过循环#1结果来完成此操作,因为我有很多数据,并且要花很多时间才能完成。任何人都可以帮助我在一个查询中做到这一点吗?

最佳答案

我想到的是一个相关的子查询,以获取先前的价格。以下版本使用having子句进行最终比较(也可以使用子查询):

select h.*,
       (select h2.price
        from history h2
        where h2.property_id = h.property_id and
              h2.created_at < h.created_at
        order by h2.created_at desc
        limit 1
       ) as prev_price
from history h
where h.created_at > date_sub(now(), interval 1 day)
having prev_price is null or prev_price <> price;


为了提高性能,您需要在history(created_at)history(property_id, created_at, price)上建立索引。

关于mysql - MySQL:如何从历史记录表中获取价格变化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36530239/

10-12 07:26