2

我正在尝试从数据库中获取最后一条消息并按用户分组

http://i.stack.imgur.com/Wjzin4.png

$query = $this->query("SELECT * FROM `messages` 
WHERE `receiver` = '763' 
GROUP BY `sender` 
ORDER BY `id` DESC 
LIMIT 0, 50");

输出:

http://i.stack.imgur.com/GLhyan.png

所以有问题..应该是e而不是dc而不是a

4

1 回答 1

3
SELECT  a.*
FROM    messages a
        INNER JOIN
        (
            SELECT  sender, MAX(ID) MAX_ID
            FROM    messages
            GROUP   BY sender
        ) b ON a.sender = b.sender AND
                a.id = b.MAX_ID
// WHERE clause...
// ORDER BY ....
// LIMIT  .....

SQLFiddle 演示链接

于 2013-01-23T14:37:46.247 回答