项目场景:现在有一张数据表如下所示,需要获取每个用户最新发布的信息;
id | user_id | situation | created_at |
---|---|---|---|
1 | 1 | 内容1_1 | 2022-08-01 |
2 | 2 | 内容2_1 | 2022-08-01 |
3 | 3 | 内容3_1 | 2022-08-01 |
4 | 4 | 内容4_1 | 2022-08-01 |
5 | 1 | 内容1_2 | 2022-08-02 |
6 | 2 | 内容2_2 | 2022-08-02 |
7 | 2 | 内容2_3 | 2022-08-03 |
8 | 3 | 内容3_2 | 2022-08-02 |
9 | 4 | 内容4_2 | 2022-08-02 |
SELECT * FROM test Ta,(SELECT max(id) id FROM test GROUP BY user_id) Tb where Ta.id = Tb.id;
SELECT id,situation,user_id,created_at FROM test WHERE id IN (select max(id) id from test group by user_id order by id desc);