Im developing a chat tool and im having problems with the sql returning the right results with group by and order by. The table has a structure shown below;
tablename: chat
id | from | to | sent | read | message
‘from’ and ‘to’ are a signed integers (userids)
‘sent’ is a timestamp when the message was sent.
‘message’ is text msg
‘read’ is an int (0 for unread, 1 for read).
im trying to return a list of the most recent messages grouped by users
eg
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
should return this after the query
id from to message sent read
7326 251 1 u there 1349741686 0
7324 21 1 try again 1349697192 1
here is my query
$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";
it doesnt return the desired results;
You should create a subquery which determines the latest
sentbyusersthen join it withchattable.SQLFiddle Demo