2

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

表名:聊天

id | from | to | sent | read | message

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

它没有返回所需的结果;

4

1 回答 1

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 演示

于 2012-10-09T01:24:05.370 回答