3

我有一个名为sk_messages.It 的表,其结构如下:

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
4

3 回答 3

6

尝试group通过 id 访问用户。

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 '
于 2013-02-13T09:16:29.810 回答
3

试试这个:

SELECT 
  m1.msg_from_user_id, 
  m1.msg_text, 
  m1.msg_date
FROM sk_messages AS m1
INNER JOIN
(
   SELECT msg_from_user_id, MAX(msg_date) AS LatestDate
   FROM sk_messages
   WHERE msg_to_user_id =  '$user_id' 
     AND msg_status =  'unread'
   GROUP BY msg_from_user_id
) AS m2  ON m1.msg_from_user_id = m2.msg_from_user_id
        AND m1.msg_date         = m2.LatestDate
ORDER BY m1.msg_date;

SQL 小提琴演示

于 2013-02-13T09:16:30.070 回答
0

用这个

SELECT 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  GROUP BY msg_from_user_id

于 2013-02-13T09:18:10.787 回答