MySQL:按加入的最大日期排序 table
MySQL: Order by max date of a joined table
我有两个 tables - groups
和 messages
。
消息具有以下字段 group_id
和 date_created
。因此,可以将很多消息添加到一个组中。我想 select 来自 table 的所有组 - 最相关的在最上面,即按最新消息日期排序。我试过这样的东西
SELECT g.*, MAX(m.date_created) AS mdt FROM groups g
LEFT JOIN messages m ON g.id = m.group_id
ORDER BY mdt DESC;
但是这个查询 returns 只有一行和整个 table 中的最大消息日期。
你错过了group by
:
SELECT g.*, MAX(m.date_created) AS mdt
FROM groups g LEFT JOIN
messages m
ON g.id = m.group_id
GROUP BY g.id
ORDER BY mdt DESC;
我有两个 tables - groups
和 messages
。
消息具有以下字段 group_id
和 date_created
。因此,可以将很多消息添加到一个组中。我想 select 来自 table 的所有组 - 最相关的在最上面,即按最新消息日期排序。我试过这样的东西
SELECT g.*, MAX(m.date_created) AS mdt FROM groups g
LEFT JOIN messages m ON g.id = m.group_id
ORDER BY mdt DESC;
但是这个查询 returns 只有一行和整个 table 中的最大消息日期。
你错过了group by
:
SELECT g.*, MAX(m.date_created) AS mdt
FROM groups g LEFT JOIN
messages m
ON g.id = m.group_id
GROUP BY g.id
ORDER BY mdt DESC;