
●tb_user_section
| user_id | section_id | created |
| 1 | 1 | 2020-05-11 20:00:00 |
| 1 | 2 | 2020-05-12 20:00:00 |
| 1 | 3 | 2020-05-13 20:00:00 |
| 2 | 1 | 2020-05-15 20:00:00 |
| 3 | 2 | 2020-05-18 20:00:00 |
| 3 | 4 | 2020-05-19 20:00:00 |
user_idのグループ毎に最新の日付のデータをまとめたい
求めたい形
| user_id | section_id | created |
| 1 | 3 | 2020-05-13 20:00:00 |
| 2 | 1 | 2020-05-15 20:00:00 |
| 3 | 4 | 2020-05-19 20:00:00 |
これが今回の目指す形だよ🐱
正解
SELECT
user_id,
section_id,
created
FROM
tb_user_section
WHERE created = (
SELECT MAX(created)
FROM tb_user_section AS us
WHERE tb_user_section.user_id = us.user_id
)
ポイント
SELECT
user_id,
section_id,
created
FROM
tb_user_section
WHERE created = ( ←●最大値カラムの値と等しくなるデータを抽出
SELECT
MAX(created) ←●最大値カラムの値を求める
FROM tb_user_section AS us ←●別名をつける
WHERE tb_user_section.user_id = us.user_id ←●元テーブルと別名テーブルに対してグループ化対象カラムでデータ抽出抽出
)
========================
SELECT MAX(created) FROM tb_user_section
結果
MAX(created) 2020-05-19 20:00:00
はい。
SELECT user_id, section_id MAX(created) FROM tb_user_section
結果
user_id section_id MAX(created) 1 1 2020-05-19 20:00:00
こうじゃないよ





— 最初にサブクエリで必要な条件をすべて集め、where inをペアで適用
select * from tb_user_section
where (user_id, created) in (
select user_id, max(created)
from tb_user_section
group by user_id
);