日期:2014-05-17  浏览次数:20384 次

求一句SQL,谢谢!
表结构:<记录聊天消息>

/*对方ID*/   /*收到消息时间*/   /*消息内容*/    /*消息标记,1:已读;2:未读*/
     userid              time             content              msgflag


一句SQL得到与每个用户最近的一条聊天记录,并得到未读消息数目

谢谢!

------解决方案--------------------
select * ,c.[count]
from tab a inner join (select userid,count(1) [count] from tab where msgflag=2 group by userid) c on a.userid=c.userid
where exists 
(select 1 from (
select userid,max(time) time
from tab
group by userid)b where a.userid=b.userid and a.time=b.time )