如何分组并显示mysql中的第一个数据?
鉴于此表: 表消息如何分组并显示mysql中的第一个数据?,mysql,sql,Mysql,Sql,鉴于此表: 表消息 id | conversation_id | user_id | message | created_at ----------------------------------------------------- 1 | 1 | 1 | hello | 2017-05-09 2 | 1 | 2 | hi | 2017-05-10 3 | 2 |
id | conversation_id | user_id | message | created_at
-----------------------------------------------------
1 | 1 | 1 | hello | 2017-05-09
2 | 1 | 2 | hi | 2017-05-10
3 | 2 | 2 | me | 2017-05-11
4 | 2 | 3 | oh | 2017-05-12
5 | 1 | 1 | okay | 2017-05-13
我想获得所有第一条消息的列表,因此我的预期结果是
id | conversation_id | user_id | message | created_at
-----------------------------------------------------
1 | 1 | 1 | hello | 2017-05-09
3 | 2 | 2 | me | 2017-05-11
目前我有以下问题:
select * from messages group by conversation_id ORDER BY created_at desc
然而,这将返回:
id | conversation_id | user_id | message | created_at
-----------------------------------------------------
5 | 1 | 1 | okay | 2017-05-13
4 | 2 | 3 | oh | 2017-05-12
这是最后的消息,它们按日期排序
如何检索所需数据?以下是获取第一条消息的一种方法:
select m.*
from messages m
where m.created_at = (select min(m2.created_at) from messages m2 where m2.conversation_id = m.conversation_id);
分组依据不适用于此查询。您没有聚合任何内容。以下是获取第一条消息的一种方法:
select m.*
from messages m
where m.created_at = (select min(m2.created_at) from messages m2 where m2.conversation_id = m.conversation_id);
分组依据不适用于此查询。您没有聚合任何内容。嗯,您可能正在聚合某些内容。嗯,您可能正在聚合某些内容。从消息中选择a.*加入从消息组中选择MINid id,按b.id=a.id上的对话\u id b;从消息a中选择a.*通过b.id=a.id上的对话从消息组中选择MINid id;