GROUPBY分组后得到最新即时间最⼤的⼀条数据(需添加
limit才可⽣效)
当使⽤GROUP BY 分组,默认返回的数据是组中最⼩的记录即id最⼩的数据,
groupby分组当开发中经常会需要分组后将最新的数据放在前⾯,
为了实现需求,使⽤了嵌套查询,分别使⽤order by来排序
SELECT
id,
from_id,
to_id,
conversation_id,
created_date,
has_read,
content
FROM
( SELECT * FROM message WHERE from_id = 6 OR to_id = 6 ORDER BY created_date DESC) AS tt
GROUP BY
conversation_id
ORDER BY
created_date DESC
但执⾏结果依然是id最⼩的那条数据
最终添上limit max_size 后才⽣效
SELECT
id,
from_id,
to_id,
conversation_id,
created_date,
has_read,
content
FROM
( SELECT * FROM message WHERE from_id = 6 OR to_id = 6 ORDER BY created_date DESC limit 100) AS tt GROUP BY
conversation_id
ORDER BY
created_date DESC

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。