2012-10-09 37 views
2

我正在开发一个聊天工具,并与即时通讯问题与SQL返回正确的结果与组和按顺序。该表具有如下所示的结构;Mysql小组按顺序给出奇怪的结果

表名:“从”聊天

id | from | to | sent | read | message 

和“到”是一个带符号的整数(用户ID) “发送”是时间戳被发送的消息时。 'message'is text msg 'read'是一个int(0表示未读,1表示读取)。

我尝试返回用户

例如分组最近的消息列表

id   from  to  message  sent read 
7324  21  1  try again 1349697192 1 
7325  251  1  yo whats up 1349741502 0 
7326  251  1  u there  1349741686 0 

查询

id  from to  message  sent  read 
7326  251  1  u there 1349741686 0 
7324  21  1  try again 1349697192 1 

这里后应该返回,这是我的查询

$q ="SELECT chat.to,chat.read,chat.message,chat.sent,chat.from FROM `chat` WHERE chat.to=$userid GROUP BY chat.from ORDER BY chat.sent DESC,chat.read ASC LIMIT ".(($page-1)*$count).",$count";    

它不会返回所需的结果;

回答

3

您应该创建一个子查询,它将通过users确定最新的sent,然后使用chat表将其加入。

SELECT a.*     -- this will list all latest rows from chat table 
FROM `chat` a 
     INNER JOIN 
     (
      SELECT `from`, `to`, MAX(sent) maxSent 
      FROM `chat` 
      GROUP BY `from`, `to` 
     ) b ON a.`from` = b.`from` AND 
       a.`to` = b.`to` AND 
       a.sent = b.maxSent 
-- WHERE ....     -- add your condition(s) here 

SQLFiddle Demo

+0

在查询中,我没有看到,你可以指定“到”例如,在我的例子$用户ID的一部分。检查了解我的意思http://sqlfiddle.com/#!2/ca5a0/1 –

+0

此外,未读,即阅读= 0应显示之前阅读= 1 –

+0

@SirLojik [看到这个:添加在哪里和订单BY条款](http://sqlfiddle.com/#!2/ca5a0/5) –