I am working on an problem regarding Selecting data from two MySQL tables.
First table holds messages | messages | (id, msg_group_id, to_user_id, from_user_id, datetime)
Second table holds user data | profiles | (user_id, name, firstname, ...)
ATM it works the way, that I can select ALL messages with a certain 'to_id' and by adding a JOIN statement getting the name and firstname of the user who sends the message.
My problem now is that I can not figure out a way to ONLY select the newest message of a certain msg_group_id.
I already tried GROUP BY msg_group_id combined with ORDER BY datetime DESC.
But that only throws the very first entry in message table. But I want to last one. :-)
I hope you can help me. :-)
My actual SQL statement:
SELECT LEFT(messages.message, 10) AS message, 
`messages`.`msg_group_id`,  
`messages`.`datetime`,  
`profiles`.`name`,  
`profiles`.`firstname`  
FROM `messages`  
LEFT JOIN `profiles`  
ON `messages`.`from_user_id` = `profiles`.`user_id`  
WHERE `to_user_id` = '2'  
ORDER BY `datetime` DESC  
LIMIT 20;
Thanks in Advance
Sample INPUT:
[messages]
|id|msg_group_id|to_user_is|from_user_id|message       |datetime|
0  | 1          | 1        | 2          | Hello World1 | 2015-12-21 10:42:00
1  | 1          | 1        | 2          | Hello World2 | 2015-12-21 10:43:00
2  | 1          | 1        | 2          | Hello World3 | 2015-12-21 10:44:00
[profiles]
user_id|name    |firstname|
1      | Test   | User
2      | Thanks | Worldname
Result (what I don't want)
message|msg_group_id|datetime|name|firstname
Hello World1 | 1 | 2015-12-21 10:42:00 | Thanks | Worldname
Result (what I want)
message|msg_group_id|datetime|name|firstname
Hello World3 | 1 | 2015-12-21 10:44:00 | Thanks | Worldname
 
     
    