PHP Mysql表:消息
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
目标是检索最高价值的消息(MAX)并根据发送者,接收者对消息进行分组。因此,消息ID 1和2将组合在一起,id 3和4将组合在一起。
示例:登录userid = 2应该返回
id sender receiver time_sent Message SendDel RecDel
4 4 2 2011-08-18 15:19:28 [text] 0 0
我不知道为什么,但我的查询没有将所有消息组合在一起。这是我的疑问:
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
任何解决方案?
答案 0 :(得分:5)
你想:
因此消息ID 1和2将组合在一起,id 3和4将组合在一起。
你必须在group by子句中做一些魔术来实现这一目标。
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