从INNER JOIN中选择最后一条记录并进行分组

时间:2015-11-12 20:08:22

标签: php mysql sql mysqli

好的,所以我有一个查询,从按日期DESC排序的每个用户中选择1条消息,但为每个组选择第一条消息。我需要从每个组(每个用户)按日期选择最后一条消息 这是我的问题:

SELECT     people.id, 
           people.avatar, 
           people.firstname, 
           people.lastname, 
           LEFT(messages.message, 90) AS message, 
           messages.seen, 
           messages.date 
FROM       people 
INNER JOIN messages 
ON         people.id = messages.sender_id 
WHERE      reciever_id = '". $user_data['id'] ."' 
GROUP BY   sender_id 
ORDER BY   date DESC limit 11

1 个答案:

答案 0 :(得分:0)

请原谅我的语法,如果它有点偏,但我可能会尝试这样的事情。

SELECT people.id, 
       people.avatar, 
       people.firstname, 
       people.lastname, 
       LEFT(msg.message, 90) AS message, 
       msg.seen, 
       msg.date 
FROM  people 
INNER JOIN (SELECT message, seen, date, sender_id
                FROM messages GROUP By sender_id 
                ORDER By date DESC LIMIT 1) msg
                ON people.id = msg.sender_id
WHERE      reciever_id = '". $user_data['id'] ."'