1

在 MySQL 中,我有一个表things,其中包含一个user_id. 该表thing_updates包含对事物的更新,并具有 astatus和 a date_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是因为它比x之前和之前更新999999999。总共有2结果,这个查询似乎工作正常。

现在我想得到status今天、昨天、前一天等到 10 天前的总结果。为此,我创建了另一个名为chart_range0 到 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 不能在不相关的子查询中引用。如何修改此查询以使其正常工作?

4

0 回答 0