MySQL分组依据的排序表

问题描述 投票:-1回答:2

我有两个具有这些结构的表:

表1

+----+-----------+------------+-------------------+
| id | table2_id | created_at | some_other_fields |
+----+-----------+------------+-------------------+

表2

+----+----------+-------------------+
| id | category | some_other_fields |
+----+----------+-------------------+

我的目标是从表2中为每个类别从表1]中获取最后创建的记录。我该怎么办?

直到现在,我得到了这个查询,它返回创建日期之前排序的所有条目。

select *
from table_1 a
join table_2 b on a.table2_id = b.id
order by r.created_at desc;

我已经阅读了group by属性,但这不能保证我可以获取最后的条目。我该如何解决这个问题?

我有两个具有以下结构的表:表1 + ---- + ----------- + ------------ + ------ ------------- + | id | table2_id | created_at | some_other_fields | + ---- + ----------- + ------------ + ----------------- .. 。

mysql sql group-by greatest-n-per-group
2个回答
1
投票

假定Table2categories


0
投票

GROUP BY与聚合函数MAX一起使用应该可以解决您的问题:

© www.soinside.com 2019 - 2024. All rights reserved.