1

In MySQL, I have a table things which holds things owned by a user_id. The table thing_updates holds updates to things, and have a status and a date_submitted which is a unix timestamp of when the update was made. things do not necessarily have a corresponding row in thing_updates, such as when an update has not yet been made. Sample data:

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

I have managed to get the latest status of each thing before the date 999999999 assigned to user_id = 1 with the query below.

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

This will give me something akin to:

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

As you can see, the status y is shown because it is more recent than x and before 999999999. There are 2 results in total and this query seems to work fine.

Now I would like to get total results which have a certain status for today, yesterday, the day before, etc until 10 days ago. To do this I have created another table called chart_range which holds the numbers 0 to 9. For instance:

Table: chart_range
offset
0
1
2
...
9

I hoped to use the offset value as follows:

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

The end goal is to get a result like this:

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

However my query does not work as cr.offset cannot be referenced in an uncorrelated subquery. How can I modify this query to work?

Dion Moult
  • 109
  • 4

0 Answers0