以下のようなデータと条件があり、取得するためのSQLを書いたのですが
結果がうまく取得できません。
1. 条件
タイプBのユーザごとに、指定日付以降で最新の更新日付(updated_at)を取得する。
※deleted_atがnullのものを取得
2. データ
article_id | user_id | type | updated_at | deleted_at |
---|---|---|---|---|
1 | 1 | A | 2021-05-01 | |
2 | 1 | B | 2021-05-02 | |
3 | 2 | A | 2021-05-01 | |
4 | 1 | B | 2021-05-03 | |
5 | 2 | B | 2021-05-01 | |
6 | 3 | B | 2021-05-02 | |
7 | 3 | B | 2021-05-04 | 2021-05-04 |
8 | 1 | B | 2021-05-06 |
3. とれてほしい結果
※指定日付は2021-05-05とした場合
article_id | user_id | type | updated_at | deleted_at |
---|---|---|---|---|
4 | 1 | B | 2021-05-03 00:00:00 | |
5 | 2 | B | 2021-05-01 00:00:00 | |
6 | 3 | B | 2021-05-02 00:00:00 |
4. 書いたSQL
SQL
1SELECT 2 ar.article_id, 3 ar.user_id, 4 ar.updated_at 5FROM articles AS ar 6WHERE ar.updated_at = ( 7 SELECT MAX(updated_at) as updated_at 8 FROM articles AS sub_ar 9 WHERE sub_ar.type = 'B' 10 AND sub_ar.updated_at <= {指定の日付(Y-m-d)} 11 AND sub_ar.user_id = ar.user_id 12 AND deleted_at IS null 13);
以下のサイトをお手本にしながら書きました。
https://www.yuulinux.tokyo/17432/
https://dev.mysql.com/doc/refman/5.6/ja/example-maximum-column-group-row.html
でもうまく書けず、思うような結果が取得できませんでした。
もしよければ、アドバイスいただけると嬉しいです。
よろしくお願いします。