MySQL在过去N天内选择一种类型的最新更新

时间:2018-04-10 22:19:58

标签: mysql select getlatest

在MySQL中,我有一个表things,其中包含user_id所拥有的内容。表thing_updates保存对事物的更新,并且具有statusdate_submitted,它是更新时的unix时间戳。 things thing_updates中不一定有相应的行,例如尚未进行更新时。样本数据:

Table: things
id | user_id
1  | 1
2  | 1
3  | NULL

Table: thing_updates
id | thing_id | status | date_submitted
1  | 1        | x      | 123456789
2  | 1        | y      | 234567890
3  | 3        | x      | 123456789

我已设法在999999999分配给user_id = 1的日期之前通过以下查询获取每件事物的最新状态。

select t.id, tu.status, t.user_id
from things as t
left join thing_updates as tu
on tu.thing_id = t.id
where (
    date_submitted in (
        select max(tu2.date_submitted)
        from thing_updates as tu2
            where date_submitted < 999999999
        group by thing_id
    )
    or date_submitted is null
)
and t.user_id = 1

这会给我一些类似于:

id | status | user_id
1  | y      | 1
2  | NULL   | 1

如您所见,状态y已显示,因为它比x999999999之前更新。总共有2个结果,此查询似乎运行正常。

现在我希望获得今天,昨天,前一天等具有一定status的总结果,直到10天前。为此,我创建了另一个名为chart_range的表,其中包含数字0到9.例如:

Table: chart_range
offset
0
1
2
...
9

我希望使用offset值,如下所示:

select cr.offset, count(x.id) as total_x
from chart_range as cr
left join (
    select t.id, tu.status, t.user_id
    from things as t
    left join thing_updates as tu
    on tu.thing_id = t.id
    where (
        date_submitted in (
            select max(tu2.date_submitted)
            from thing_updates as tu2
                where date_submitted < unix_timestamp(date_add(now(), interval - cr.offset + 1 day))
            group by thing_id
        )
        or date_submitted is null
    )
    and t.user_id = 1    
) as x on tu.status = 'x'
group by cr.offset
order by cr.offset asc

最终目标是得到这样的结果:

offset | total_x
0      | 2 <-- such as in the 999999999 example above
1      | 5
2      | 7
3      | 4
...
9      | 0

但是我的查询不起作用,因为cr.offset不能在不相关的子查询中引用。如何修改此查询才能生效?

0 个答案:

没有答案