开发者

php Mysql Grouping and Ordering user messages together

PHP Mysql Table:Messages

id   sender   receiver      time_sent          Message  SendDel RecDel
1     1          3      2011-08-17 14:00:00     [text]     0      0
2     3          1      2011-08-17 15:00:00     [text]     0      0
3     2          4      2011-08-18 14:19:28     [text]     1      0
4     4          2      2011-08-18 15:19:28     [text]     0      0

Objective is to retrieve the highest value message(MAX) and group the messages based on sender,receiver. So message id's 1 and 2 would group together and id's 3 and 4 would group together.

Example: logged in userid = 2 Should return

id   sender   receiver      time_sent          Message  SendDel RecDel
开发者_JAVA技巧4     4          2      2011-08-18 15:19:28     [text]     0      0

Im not sure why but my query does not group all the messages together. Here is my query:

SELECT id, sender, receiver, MAX(time_sent), MAX(message) 
FROM Messages
WHERE sender='$userid' OR receiver = '$userid' 
Group By sender,receiver 
Order BY time_sent DESC

Any Solutions?


You want:

So message id's 1 and 2 would group together and id's 3 and 4 would group together.

You'll have to do some magic in the group by clause to make this happen.

SELECT id, sender, receiver, MAX(time_sent), MAX(message) 
FROM Messages
WHERE sender='$userid' OR receiver = '$userid' 
Group By (if(sender > receiver,  sender, receiver))
       , (if(sender > receiver,  receiver, sender))
Order BY time_sent DESC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜