Mysql Group By和Order通过给出奇怪的结果

时间:2012-10-09 01:20:41

标签: php mysql sql group-by sql-order-by

我正在开发一个聊天工具,我有问题,sql返回正确的结果与group by和order by。该表的结构如下所示;

tablename:chat

id | from | to | sent | read | message

'from'和'to'是有符号整数(userids) 'sent'是邮件发送时的时间戳。 'message'是文本消息 '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";            

它不会返回所需的结果;

1 个答案:

答案 0 :(得分:3)

您应该创建一个子查询,通过sent确定最新的users,然后将其与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