Selecting last record from INNER JOIN and grouping

2019-04-16 17:36发布

Okay so I have a query that selects 1 message from each user that is ordered by date DESC but selects the first message for each group.. I need to select the last message by date from each group (each user) This is my query:

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条回答
欢心
2楼-- · 2019-04-16 18:03

Please excuse my syntax if it is a bit off, but I would probably try something like this.

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'] ."' 
查看更多
登录 后发表回答