1. 业务场景
项目中有个小型的私信功能,需要查询出聊天列表且展示与所有聊天对象的最后一条聊天记录;
因此需要按照聊天对象分组,找出与每个聊天的最后一条消息,group by和order by就得同时使用;
2. SQL
- 先排序再分组取第一条
SELECT
p.id,
COUNT( p.friend ) AS msgCnt,
p.user,
p.friend,
p.sender,
p.receiver,
p.send_time AS sendTime,
p.content,
u.nick_name AS receiverName,
u.avatar_url AS receiverImage
FROM
( SELECT * FROM private_message WHERE user=