1

MySQL には、thingsが所有するものを保持するテーブルがありますuser_id。テーブルthing_updatesは物事の更新を保持し、更新が行われたときのUNIXタイムスタンプであるastatusと aを持っています。更新がまだ行われていない場合など、対応する行が必ずしも にあるとは限りません。サンプルデータ:date_submittedthingsthing_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

ご覧のとおり、ステータスが表示されているのは、および beforeyより新しいためです。合計で結果があり、このクエリは正常に機能しているようです。x9999999992

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 を参照できないため、クエリは機能しません。このクエリを変更して機能させるにはどうすればよいですか?

4

0 に答える 0