我有一个名为sk_messages的表,它的结构如下:

msg_id     msg_from_user_id  msg_to_user_id  msg_text   msg_date     msg_status

 1              12                14          hai...   23-12-2013      unread

 2              12                14         ....     ...             unread

 3              13                 14        ...      ..               unread

我的要求是,我想显示当前用户的所有消息,条件是即使发件人发送了多个状态为“未读”的消息,也应该显示来自发件人的单个消息。也就是说,从上面的上下文中,ID为12的用户的单个消息应该是已展开。我已尝试以下查询,但它不起作用。
SELECT DISTINCT (msg_from_user_id), msg_text, msg_date
 FROM sk_messages
 WHERE msg_to_user_id =  '$user_id'
 AND msg_status =  'unread'
 ORDER BY msg_date


$user_id is the id of the login user

最佳答案

按ID尝试group用户。

SELECT msg_text, msg_date
 FROM sk_messages
 WHERE msg_to_user_id =  '$user_id'
 AND msg_status =  'unread'
GROUP BY msg_from_user_id
 ORDER BY msg_date

测试代码以获取最新消息
'SELECT * FROM ( SELECT * FROM message WHERE user_id = 1 ORDER BY created DESC LIMIT 1) as msg  GROUP BY user_id '

10-05 18:50